{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b017f044",
   "metadata": {},
   "source": [
    "# IFCB → CalCOFI summary table\n",
    "\n",
    "Builds the per-sample summary (taxon × ESD size bin → abundance, biovolume, ESD) from:\n",
    "\n",
    "| Input | What it holds |\n",
    "|---|---|\n",
    "| **Feature folder** | `DYYYYMMDDTHHMMSS_IFCBxxx_features_v2.csv` — one row per ROI (`roi_number`, `EquivDiameter`, `Biovolume`, …) |\n",
    "| **Autoclass folder** | `DYYYYMMDDTHHMMSS_IFCBxxx_class_vNone.csv` — `pid` (`…_00002`) + one score column per class |\n",
    "| **Metadata** | one row per IFCB file: cruise, date, line/station, depth, lat/lon, volume analyzed |\n",
    "| **WoRMS match** | autoclass name → WoRMS matched name, AphiaID, taxonomy |\n",
    "\n",
    "**Steps**\n",
    "1. Settings (the only cell you normally edit)\n",
    "2. Helpers\n",
    "3. Load + check metadata\n",
    "4. Pair feature and autoclass files\n",
    "5. Load WoRMS match table and check every class maps\n",
    "6. Assign each ROI its top class and join features\n",
    "7. Filter taxa\n",
    "8. Aggregate into the summary\n",
    "9. QC and export\n",
    "\n",
    "Run top to bottom. Each step prints a short report so you can catch problems before the export."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92d98360",
   "metadata": {},
   "source": [
    "## 1. Settings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "3fe435b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "import os\n",
    "os.chdir('/Users/houlin/Desktop/Research/CalCOFI/CalCOFI_IFCB/CalCOFI/CalCOFI_CTD')\n",
    "\n",
    "# ---- Input paths ----\n",
    "FEATURE_DIR   = \"feature\"         # folder of *_features*.csv\n",
    "CLASS_DIR     = \"class_changed\"         # folder of *_class*.csv\n",
    "DATA_DIR    =   'data'\n",
    "METADATA_FILE = \"CalCOFI_CTD_metadata_filled_102226.csv\" ## enter the right metadata\n",
    "WORMS_FILE    = \"/Users/houlin/Desktop/Research/CalCOFI/CalCOFI_IFCB/CalCOFI_IFCB_WoRMS_match.xlsx\"\n",
    "\n",
    "# Optional: table holding per-class classifier accuracy.\n",
    "# Any csv/xlsx with a class-name column and an accuracy column works; the old summary file does.\n",
    "# Set to None to leave the column blank.\n",
    "ACCURACY_FILE      = \"/Users/houlin/Desktop/Research/CalCOFI/CalCOFI_IFCB/CalCOFI/CalCOFI_CTD/CalCOFI_CTD_IFCB_data_summary.xlsx\"\n",
    "ACCURACY_CLASS_COL = \"Taxa\"\n",
    "ACCURACY_VALUE_COL = \"Autoclass Accuracy\"\n",
    "\n",
    "# ---- Output ----\n",
    "OUTPUT_DIR    = Path(\"CalCOFI_CTD_summary_output\")\n",
    "OUTPUT_NAME   = \"CalCOFI_CTD_IFCB_data_summary_new\"   # .csv and .xlsx are written\n",
    "SAVE_ROI_TABLE = True     # also save the per-ROI table (handy for checking / re-binning later)\n",
    "\n",
    "# ---- File patterns ----\n",
    "FEATURE_GLOB = \"*_features*.csv\"\n",
    "CLASS_GLOB   = \"*_class*.csv\"\n",
    "\n",
    "# ---- Classification ----\n",
    "AUTOCLASS_VERSION = 1\n",
    "MIN_CONFIDENCE = None      # e.g. 0.5 -> ROIs whose top score is below this become \"unclassified\"; None = keep all\n",
    "\n",
    "# ---- Size / unit conversion ----\n",
    "PIXELS_PER_MICRON = 3.4    # IFCB standard; check your instrument's calibration\n",
    "# Size bins on ESD (µm): left-closed, i.e. [0,10), [10,20), [20,40), [40,inf)\n",
    "SIZE_BIN_EDGES  = [0, 10, 20, 40, float(\"inf\")]\n",
    "SIZE_BIN_LABELS = [\"<10\", \"10-20\", \"20-40\", \"40>\"]\n",
    "SD_DDOF = 1                # 1 = sample SD, 0 = population SD (single-ROI groups get SD 0 either way)\n",
    "\n",
    "# ---- Taxa filtering ----\n",
    "# Classes are assigned first (argmax over ALL classes), THEN filtered, so a detritus\n",
    "# ROI is dropped rather than being re-assigned to its 2nd-best class.\n",
    "EXCLUDE_WORMS_EXCLUDED = True   # drop classes marked \"excluded\" in the WoRMS 'WoRMS Status' column\n",
    "EXCLUDE_NON_CELLS      = False  # drop classes with 'Cell (yes/no)' == 'no'\n",
    "EXCLUDE_TAXA = [                # extra autoclass names to drop (exact names as in the class file)\n",
    "    # \"Bacteria_colony\",\n",
    "    # \"Nauplii\",\n",
    "]\n",
    "KEEP_ONLY_TAXA = None           # e.g. [\"Chaetoceros\", \"Pseudo-nitzschia\"] to keep only these; None = keep all\n",
    "\n",
    "# ---- Aggregation level ----\n",
    "# \"autoclass\": one row per autoclass class (like the old summary)\n",
    "# \"worms\":     merge classes sharing a WoRMS name (e.g. Strombidium_morphotype1 + _morphotype2)\n",
    "GROUP_BY = \"worms\"\n",
    "\n",
    "# ---- WoRMS name matching ----\n",
    "# If an autoclass name isn't in the match table, retry after stripping a \"_TAG_...\" suffix\n",
    "# (e.g. Chaetoceros_TAG_interaction -> Chaetoceros). Fallback matches are listed in Step 5.\n",
    "TAG_FALLBACK = True\n",
    "\n",
    "# ---- Metadata tidying ----\n",
    "DEPTHTYPE_MAP = {\"surface\": \"Surface\", \"dcm\": \"DCM\", \"chl max\": \"DCM\"}   # case/underscore-insensitive relabel of sample_type; {} to leave as-is"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31734226",
   "metadata": {},
   "source": [
    "## 2. Helpers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3107bc98",
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "pd.set_option(\"display.max_columns\", 50)\n",
    "pd.set_option(\"display.width\", 200)\n",
    "\n",
    "BIN_RE = re.compile(r\"(D\\d{8}T\\d{6}_IFCB\\d+)\")\n",
    "\n",
    "def bin_id(name):\n",
    "    \"\"\"Extract 'DYYYYMMDDTHHMMSS_IFCBxxx' from a filename / pid; None if not found.\"\"\"\n",
    "    m = BIN_RE.search(str(name))\n",
    "    return m.group(1) if m else None\n",
    "\n",
    "def norm_name(s):\n",
    "    \"\"\"Normalise a taxon name for matching: lowercase, '_', '-' and spaces collapsed to one space.\"\"\"\n",
    "    if pd.isna(s):\n",
    "        return None\n",
    "    return re.sub(r\"[\\s_\\-]+\", \" \", str(s)).strip().lower()\n",
    "\n",
    "def read_table(path, **kw):\n",
    "    path = Path(path)\n",
    "    if path.suffix.lower() in (\".xlsx\", \".xls\"):\n",
    "        return pd.read_excel(path, **kw)\n",
    "    return pd.read_csv(path, **kw)\n",
    "\n",
    "def index_folder(folder, pattern):\n",
    "    \"\"\"Map bin id -> file path. Warns on unparseable names and duplicates.\"\"\"\n",
    "    out, bad, dup = {}, [], []\n",
    "    for p in sorted(Path(folder).glob(pattern)):\n",
    "        b = bin_id(p.name)\n",
    "        if b is None:\n",
    "            bad.append(p.name)\n",
    "        elif b in out:\n",
    "            dup.append(p.name)\n",
    "        else:\n",
    "            out[b] = p\n",
    "    if bad: print(f\"  ! {len(bad)} file(s) without a valid bin id ignored: {bad[:5]}\")\n",
    "    if dup: print(f\"  ! {len(dup)} duplicate bin(s) ignored: {dup[:5]}\")\n",
    "    return out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d936735b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# import h5py, pandas as pd\n",
    "\n",
    "# path = \"/Users/houlin/Desktop/Research/CalCOFI/CalCOFI_IFCB/CalCOFI/CalCOFI_CTD/calcofi-cruises-ctd/2026/D20260712/D20260712T202357_IFCB151_class.h5\"\n",
    "\n",
    "# with h5py.File(path, \"r\") as f:\n",
    "#     labels  = [l.decode() for l in f[\"class_labels\"][:]]\n",
    "#     scores  = f[\"output_scores\"][:].astype(float)   # stored as float16\n",
    "#     classes = f[\"output_classes\"][:].astype(int)\n",
    "#     rois    = f[\"roi_numbers\"][:]\n",
    "#     meta    = dict(f[\"metadata\"].attrs)\n",
    "\n",
    "# df = pd.DataFrame(scores, columns=labels, index=pd.Index(rois, name=\"roi\"))\n",
    "# df.insert(0, \"top_score\", scores.max(axis=1))\n",
    "# df.insert(0, \"pred_class\", [labels[i] for i in classes])\n",
    "\n",
    "# print(meta)\n",
    "# print(df[[\"pred_class\", \"top_score\"]].head())\n",
    "# print(df[\"pred_class\"].value_counts())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bcb7584",
   "metadata": {},
   "source": [
    "## 3. Load and check metadata\n",
    "\n",
    "Columns used: `Cruise`, `Station` (\"line station\", split into `Line` / `Station`), `Latitude`, `Longitude`, `Cast_Date` (PT), `Bottle`, `Depth`, `Filename`, `sample_type` (→ `Depthstype`), `skip`.\n",
    "Rows flagged in `skip` and rows with a missing/malformed `Filename` are reported and dropped; `Cast_Date` is checked against the bin timestamp (UTC).\n",
    "Volume analyzed (`Volume_ml`) comes from the `ml_analyzed` column; blanks are filled from the `.hdr` files."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "59340861",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  ! 1 duplicate bin(s) ignored: ['D20250418T230330_IFCB151_features_v2.csv']\n",
      "2 bins missing features\n",
      "[1/2] D20260406T182453_IFCB151\n"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[4], line 53\u001b[0m\n\u001b[1;32m     51\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m suffix, outdir \u001b[38;5;129;01min\u001b[39;00m TARGETS\u001b[38;5;241m.\u001b[39mitems():\n\u001b[1;32m     52\u001b[0m     name \u001b[38;5;241m=\u001b[39m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mf\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;132;01m{\u001b[39;00msuffix\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[0;32m---> 53\u001b[0m     status \u001b[38;5;241m=\u001b[39m \u001b[43mdownload\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43mf\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;132;43;01m{\u001b[39;49;00m\u001b[43mBASE_URL\u001b[49m\u001b[38;5;132;43;01m}\u001b[39;49;00m\u001b[38;5;124;43m/\u001b[39;49m\u001b[38;5;132;43;01m{\u001b[39;49;00m\u001b[43mname\u001b[49m\u001b[38;5;132;43;01m}\u001b[39;49;00m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43moutdir\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m/\u001b[39;49m\u001b[43m \u001b[49m\u001b[43mname\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43ms\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m     54\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m status \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;129;01min\u001b[39;00m (\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mok\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mexists\u001b[39m\u001b[38;5;124m\"\u001b[39m):\n\u001b[1;32m     55\u001b[0m         failed\u001b[38;5;241m.\u001b[39mappend((name, status))\n",
      "Cell \u001b[0;32mIn[4], line 38\u001b[0m, in \u001b[0;36mdownload\u001b[0;34m(url, dest, session, retries)\u001b[0m\n\u001b[1;32m     36\u001b[0m     r\u001b[38;5;241m.\u001b[39mraise_for_status()\n\u001b[1;32m     37\u001b[0m     \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28mopen\u001b[39m(tmp, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mwb\u001b[39m\u001b[38;5;124m\"\u001b[39m) \u001b[38;5;28;01mas\u001b[39;00m fh:\n\u001b[0;32m---> 38\u001b[0m \u001b[43m        \u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mchunk\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mr\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43miter_content\u001b[49m\u001b[43m(\u001b[49m\u001b[43mchunk_size\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m \u001b[49m\u001b[38;5;241;43m<<\u001b[39;49m\u001b[43m \u001b[49m\u001b[38;5;241;43m16\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n\u001b[1;32m     39\u001b[0m \u001b[43m            \u001b[49m\u001b[43mfh\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mwrite\u001b[49m\u001b[43m(\u001b[49m\u001b[43mchunk\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m     40\u001b[0m tmp\u001b[38;5;241m.\u001b[39mrename(dest)\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/site-packages/requests/models.py:820\u001b[0m, in \u001b[0;36mResponse.iter_content.<locals>.generate\u001b[0;34m()\u001b[0m\n\u001b[1;32m    818\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mhasattr\u001b[39m(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mraw, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mstream\u001b[39m\u001b[38;5;124m\"\u001b[39m):\n\u001b[1;32m    819\u001b[0m     \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m--> 820\u001b[0m         \u001b[38;5;28;01myield from\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mraw\u001b[38;5;241m.\u001b[39mstream(chunk_size, decode_content\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m)\n\u001b[1;32m    821\u001b[0m     \u001b[38;5;28;01mexcept\u001b[39;00m ProtocolError \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m    822\u001b[0m         \u001b[38;5;28;01mraise\u001b[39;00m ChunkedEncodingError(e)\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/site-packages/urllib3/response.py:628\u001b[0m, in \u001b[0;36mHTTPResponse.stream\u001b[0;34m(self, amt, decode_content)\u001b[0m\n\u001b[1;32m    626\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m    627\u001b[0m     \u001b[38;5;28;01mwhile\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m is_fp_closed(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_fp):\n\u001b[0;32m--> 628\u001b[0m         data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mread\u001b[49m\u001b[43m(\u001b[49m\u001b[43mamt\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mamt\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mdecode_content\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdecode_content\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    630\u001b[0m         \u001b[38;5;28;01mif\u001b[39;00m data:\n\u001b[1;32m    631\u001b[0m             \u001b[38;5;28;01myield\u001b[39;00m data\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/site-packages/urllib3/response.py:567\u001b[0m, in \u001b[0;36mHTTPResponse.read\u001b[0;34m(self, amt, decode_content, cache_content)\u001b[0m\n\u001b[1;32m    564\u001b[0m fp_closed \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mgetattr\u001b[39m(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_fp, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mclosed\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;28;01mFalse\u001b[39;00m)\n\u001b[1;32m    566\u001b[0m \u001b[38;5;28;01mwith\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_error_catcher():\n\u001b[0;32m--> 567\u001b[0m     data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_fp_read\u001b[49m\u001b[43m(\u001b[49m\u001b[43mamt\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m fp_closed \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;124mb\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m    568\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m amt \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m    569\u001b[0m         flush_decoder \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mTrue\u001b[39;00m\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/site-packages/urllib3/response.py:533\u001b[0m, in \u001b[0;36mHTTPResponse._fp_read\u001b[0;34m(self, amt)\u001b[0m\n\u001b[1;32m    530\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m buffer\u001b[38;5;241m.\u001b[39mgetvalue()\n\u001b[1;32m    531\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m    532\u001b[0m     \u001b[38;5;66;03m# StringIO doesn't like amt=None\u001b[39;00m\n\u001b[0;32m--> 533\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_fp\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mread\u001b[49m\u001b[43m(\u001b[49m\u001b[43mamt\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mif\u001b[39;00m amt \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_fp\u001b[38;5;241m.\u001b[39mread()\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/http/client.py:479\u001b[0m, in \u001b[0;36mHTTPResponse.read\u001b[0;34m(self, amt)\u001b[0m\n\u001b[1;32m    476\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mlength \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m amt \u001b[38;5;241m>\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mlength:\n\u001b[1;32m    477\u001b[0m     \u001b[38;5;66;03m# clip the read to the \"end of response\"\u001b[39;00m\n\u001b[1;32m    478\u001b[0m     amt \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mlength\n\u001b[0;32m--> 479\u001b[0m s \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfp\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mread\u001b[49m\u001b[43m(\u001b[49m\u001b[43mamt\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    480\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m s \u001b[38;5;129;01mand\u001b[39;00m amt:\n\u001b[1;32m    481\u001b[0m     \u001b[38;5;66;03m# Ideally, we would raise IncompleteRead if the content-length\u001b[39;00m\n\u001b[1;32m    482\u001b[0m     \u001b[38;5;66;03m# wasn't satisfied, but it might break compatibility.\u001b[39;00m\n\u001b[1;32m    483\u001b[0m     \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_close_conn()\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/socket.py:707\u001b[0m, in \u001b[0;36mSocketIO.readinto\u001b[0;34m(self, b)\u001b[0m\n\u001b[1;32m    705\u001b[0m \u001b[38;5;28;01mwhile\u001b[39;00m \u001b[38;5;28;01mTrue\u001b[39;00m:\n\u001b[1;32m    706\u001b[0m     \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[0;32m--> 707\u001b[0m         \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_sock\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrecv_into\u001b[49m\u001b[43m(\u001b[49m\u001b[43mb\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    708\u001b[0m     \u001b[38;5;28;01mexcept\u001b[39;00m timeout:\n\u001b[1;32m    709\u001b[0m         \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_timeout_occurred \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mTrue\u001b[39;00m\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/ssl.py:1252\u001b[0m, in \u001b[0;36mSSLSocket.recv_into\u001b[0;34m(self, buffer, nbytes, flags)\u001b[0m\n\u001b[1;32m   1248\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m flags \u001b[38;5;241m!=\u001b[39m \u001b[38;5;241m0\u001b[39m:\n\u001b[1;32m   1249\u001b[0m         \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\n\u001b[1;32m   1250\u001b[0m           \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mnon-zero flags not allowed in calls to recv_into() on \u001b[39m\u001b[38;5;132;01m%s\u001b[39;00m\u001b[38;5;124m\"\u001b[39m \u001b[38;5;241m%\u001b[39m\n\u001b[1;32m   1251\u001b[0m           \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m\u001b[38;5;18m__class__\u001b[39m)\n\u001b[0;32m-> 1252\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mread\u001b[49m\u001b[43m(\u001b[49m\u001b[43mnbytes\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mbuffer\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m   1253\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m   1254\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28msuper\u001b[39m()\u001b[38;5;241m.\u001b[39mrecv_into(buffer, nbytes, flags)\n",
      "File \u001b[0;32m~/miniconda3/lib/python3.12/ssl.py:1104\u001b[0m, in \u001b[0;36mSSLSocket.read\u001b[0;34m(self, len, buffer)\u001b[0m\n\u001b[1;32m   1102\u001b[0m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[1;32m   1103\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m buffer \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[0;32m-> 1104\u001b[0m         \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_sslobj\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mread\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;28;43mlen\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mbuffer\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m   1105\u001b[0m     \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m   1106\u001b[0m         \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_sslobj\u001b[38;5;241m.\u001b[39mread(\u001b[38;5;28mlen\u001b[39m)\n",
      "\u001b[0;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "#### loading new data from the dashboard\n",
    "import requests\n",
    "from pathlib import Path\n",
    "import time\n",
    "\n",
    "BASE_URL = \"https://ifcb.caloos.org/calcofi-cruises-ctd\"\n",
    "\n",
    "# suffix on server  ->  local destination folder\n",
    "TARGETS = {\n",
    "    \"_features.csv\":     Path(FEATURE_DIR),\n",
    "    \"_class_scores.csv\": Path(CLASS_DIR),\n",
    "    \".hdr\":              Path(DATA_DIR),\n",
    "}\n",
    "\n",
    "\n",
    "meta = read_table(METADATA_FILE)\n",
    "meta.columns = meta.columns.str.strip()\n",
    "meta_files = {str(f).strip() for f in meta[\"Filename\"].dropna() if str(f).strip()}\n",
    "\n",
    "remove=['D202050415T224344_IFCB151','D20220818T160435_IFCB151','D20241120T091739_IFCB151',\n",
    "        'D20241120T094139_IFCB151','D20250116T185138_IFCB151','D20250122T143926_FICB151',\n",
    "        'D20260406T170706_IFCB151','D20260406T182453_IFCB151']\n",
    "feat_files = index_folder(FEATURE_DIR, FEATURE_GLOB)\n",
    "new_files = sorted(meta_files - set(feat_files.keys())-set(remove))\n",
    "print(f\"{len(new_files)} bins missing features\")\n",
    "\n",
    "def download(url, dest, session, retries=3):\n",
    "    \"\"\"Stream url to dest; write to a .part file first so failed downloads don't leave partial files.\"\"\"\n",
    "    if dest.exists() and dest.stat().st_size > 0:\n",
    "        return \"exists\"\n",
    "    tmp = dest.with_name(dest.name + \".part\")\n",
    "    for attempt in range(1, retries + 1):\n",
    "        try:\n",
    "            with session.get(url, stream=True, timeout=60) as r:\n",
    "                if r.status_code == 404:\n",
    "                    return \"404\"\n",
    "                r.raise_for_status()\n",
    "                with open(tmp, \"wb\") as fh:\n",
    "                    for chunk in r.iter_content(chunk_size=1 << 16):\n",
    "                        fh.write(chunk)\n",
    "            tmp.rename(dest)\n",
    "            return \"ok\"\n",
    "        except requests.RequestException as e:\n",
    "            if attempt == retries:\n",
    "                tmp.unlink(missing_ok=True)\n",
    "                return f\"error: {e}\"\n",
    "            time.sleep(2 * attempt)\n",
    "            \n",
    "failed = []\n",
    "with requests.Session() as s:\n",
    "    for i, f in enumerate(new_files, 1):\n",
    "        for suffix, outdir in TARGETS.items():\n",
    "            name = f\"{f}{suffix}\"\n",
    "            status = download(f\"{BASE_URL}/{name}\", outdir / name, s)\n",
    "            if status not in (\"ok\", \"exists\"):\n",
    "                failed.append((name, status))\n",
    "        print(f\"[{i}/{len(new_files)}] {f}\")\n",
    "\n",
    "print(f\"\\nDone. {len(failed)} failed:\")\n",
    "for name, status in failed:\n",
    "    print(f\"  {name}: {status}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d2cb6e5e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "class_changed/D20250122T143926_IFCB151_class_changed.csv\n",
      "class_changed/D20260415T224344_IFCB151_class_changed.csv\n"
     ]
    }
   ],
   "source": [
    "\n",
    "def class_scores_to_topn(scores_csv, out_csv=None, n=5):\n",
    "    \"\"\"Convert an IFCB *_class_scores.csv (pid + one column per class)\n",
    "    into a top-N table: pid, top_class, top_score, class2..N, score2..N.\"\"\"\n",
    "    df = pd.read_csv(scores_csv)\n",
    "    scores = df.drop(columns=\"pid\")\n",
    "    vals = scores.to_numpy(dtype=float)\n",
    "    classes = scores.columns.to_numpy()\n",
    "\n",
    "    # column indices sorted by score, highest first\n",
    "    order = np.argsort(-vals, axis=1, kind=\"stable\")[:, :n]\n",
    "    top_vals = np.take_along_axis(vals, order, axis=1)\n",
    "    top_cls = classes[order]\n",
    "\n",
    "    out = pd.DataFrame({\"pid\": df[\"pid\"],\n",
    "                        \"top_class\": top_cls[:, 0],\n",
    "                        \"top_score\": top_vals[:, 0]})\n",
    "    for k in range(1, n):\n",
    "        out[f\"class{k+1}\"] = top_cls[:, k]\n",
    "    for k in range(1, n):\n",
    "        out[f\"score{k+1}\"] = top_vals[:, k]\n",
    "\n",
    "    if out_csv is None:\n",
    "        out_csv = str(scores_csv).replace(\"_class_scores.csv\", \"_class_changed.csv\")\n",
    "    out.to_csv(out_csv, index=False)\n",
    "    return out\n",
    "\n",
    "CLASS_CHANGED_DIR = Path(\"class_changed\")   # set this\n",
    "CLASS_CHANGED_DIR.mkdir(parents=True, exist_ok=True)\n",
    "\n",
    "# or every file in your class folder\n",
    "for f in sorted(Path(CLASS_DIR).glob(\"*_class_scores.csv\")):\n",
    "    out = CLASS_CHANGED_DIR / f.name.replace(\"_class_scores.csv\", \"_class_changed.csv\")\n",
    "    if not out.exists():\n",
    "        print(out)\n",
    "        class_scores_to_topn(f,out)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a4e8dcbd",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "FLOW_RATE = 0.25  # mL/min, standard IFCB syringe flow rate\n",
    "\n",
    "def read_hdr(path):\n",
    "    hdr = {}\n",
    "    for line in Path(path).read_text(errors=\"ignore\").splitlines():\n",
    "        if \":\" in line:\n",
    "            k, v = line.split(\":\", 1)\n",
    "            hdr[k.strip()] = v.strip()\n",
    "    return hdr\n",
    "\n",
    "def ml_analyzed(hdr_path, flow_rate=FLOW_RATE):\n",
    "    h = read_hdr(hdr_path)\n",
    "    run = float(h[\"runTime\"])\n",
    "    inhibit = float(h[\"inhibitTime\"])\n",
    "    return flow_rate * (run - inhibit) / 60\n",
    "\n",
    "rows = []\n",
    "for f in sorted(Path(DATA_DIR).rglob(\"*.hdr\")):\n",
    "    h = read_hdr(f)\n",
    "    run, inh = float(h[\"runTime\"]), float(h[\"inhibitTime\"])\n",
    "    rows.append({\"bin\": f.stem, \"runTime\": run, \"inhibitTime\": inh,\n",
    "                 \"ml_analyzed\": FLOW_RATE * (run - inh) / 60})\n",
    "vol = pd.DataFrame(rows).set_index(\"bin\")\n",
    "vol['Filename']=vol.index\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "ffc06e38",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "! 12 bin(s) flagged skip (dropped): ['D20220815T170722_IFCB151', 'D20220818T160435_IFCB151', 'D20220818T163206_IFCB151', 'D20220819T155919_IFCB151', 'D20220829T044632_IFCB151', 'D20221015T235134_IFCB151', 'D20221111T035943_IFCB151', 'D20241120T091739_IFCB151', 'D20241120T094139_IFCB151', 'D20250116T185138_IFCB151', 'D20260406T170706_IFCB151', 'D20260406T182453_IFCB151']\n",
      "  ! these skip bins ALSO have a full metadata row - check which is right:\n"
     ]
    },
    {
     "data": {
      "application/vnd.microsoft.datawrangler.viewer.v0+json": {
       "columns": [
        {
         "name": "index",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "filename",
         "rawType": "string",
         "type": "string"
        },
        {
         "name": "Cruise",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Station",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Cast_Date",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Depth",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Depthstype",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Notes",
         "rawType": "object",
         "type": "string"
        }
       ],
       "ref": "6aebb0ae-26e3-481f-87d9-ba615a71ef0a",
       "rows": [
        [
         "117",
         "D20220829T044632_IFCB151",
         "2208BH",
         "81.7 43.5",
         "8/28/22",
         "10.0",
         "Surface",
         "SCCOOS"
        ]
       ],
       "shape": {
        "columns": 7,
        "rows": 1
       }
      },
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>filename</th>\n",
       "      <th>Cruise</th>\n",
       "      <th>Station</th>\n",
       "      <th>Cast_Date</th>\n",
       "      <th>Depth</th>\n",
       "      <th>Depthstype</th>\n",
       "      <th>Notes</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>117</th>\n",
       "      <td>D20220829T044632_IFCB151</td>\n",
       "      <td>2208BH</td>\n",
       "      <td>81.7 43.5</td>\n",
       "      <td>8/28/22</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>SCCOOS</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                     filename  Cruise    Station Cast_Date  Depth Depthstype   Notes\n",
       "117  D20220829T044632_IFCB151  2208BH  81.7 43.5   8/28/22   10.0    Surface  SCCOOS"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Metadata: 672 valid IFCB files\n",
      "Depthstype: {'Surface': 349, 'DCM': 323}\n",
      "  - Depth: 1 missing\n"
     ]
    },
    {
     "data": {
      "application/vnd.microsoft.datawrangler.viewer.v0+json": {
       "columns": [
        {
         "name": "index",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "Cruise",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Station",
         "rawType": "Float64",
         "type": "float"
        },
        {
         "name": "Latitude",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Longitude",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Cast_Date",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Cast_Time",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Cast_Time_logged",
         "rawType": "object",
         "type": "unknown"
        },
        {
         "name": "Cast",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Bottle",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Depth",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Filename",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "ml_analyzed",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Depthstype",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Notes",
         "rawType": "object",
         "type": "unknown"
        },
        {
         "name": "skip",
         "rawType": "object",
         "type": "unknown"
        },
        {
         "name": "filename",
         "rawType": "string",
         "type": "string"
        },
        {
         "name": "bin",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Line",
         "rawType": "Float64",
         "type": "float"
        },
        {
         "name": "Date",
         "rawType": "object",
         "type": "unknown"
        },
        {
         "name": "Sample_time_UTC",
         "rawType": "datetime64[ns]",
         "type": "datetime"
        },
        {
         "name": "Sample_time_PT",
         "rawType": "datetime64[ns]",
         "type": "datetime"
        },
        {
         "name": "days_cast_to_run",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "Volume_ml",
         "rawType": "float64",
         "type": "float"
        }
       ],
       "ref": "17e0bf4e-ee34-4683-9599-9f8592867bf8",
       "rows": [
        [
         "0",
         "2208BH",
         "28.0",
         "32.91304",
         "-117.39438",
         "8/14/22",
         "16:38",
         "14:43",
         null,
         "11.0",
         "10.0",
         "D20220814T233843_IFCB151",
         "4.5366",
         "Surface",
         null,
         null,
         "D20220814T233843_IFCB151",
         "D20220814T233843_IFCB151",
         "93.3",
         "2022-08-14",
         "2022-08-14 23:38:43",
         "2022-08-14 16:38:43",
         "0",
         "4.5366"
        ],
        [
         "1",
         "2208BH",
         "28.0",
         "32.91304",
         "-117.39438",
         "8/14/22",
         "17:07",
         "14:43",
         null,
         "9.0",
         "25.0",
         "D20220815T000738_IFCB151",
         "3.2233",
         "DCM",
         "Chl Max @ 25m",
         null,
         "D20220815T000738_IFCB151",
         "D20220815T000738_IFCB151",
         "93.3",
         "2022-08-14",
         "2022-08-15 00:07:38",
         "2022-08-14 17:07:38",
         "0",
         "3.2233"
        ],
        [
         "2",
         "2208BH",
         "30.0",
         "32.84637",
         "-117.53122",
         "8/14/22",
         "18:31",
         null,
         null,
         "9.0",
         "35.0",
         "D20220815T013156_IFCB151",
         "3.7947",
         "DCM",
         null,
         null,
         "D20220815T013156_IFCB151",
         "D20220815T013156_IFCB151",
         "93.3",
         "2022-08-14",
         "2022-08-15 01:31:56",
         "2022-08-14 18:31:56",
         "0",
         "3.7947"
        ],
        [
         "3",
         "2208BH",
         "37.0",
         "33.18462",
         "-118.38708",
         "8/14/22",
         "00:20",
         "22:26",
         null,
         "11.0",
         "10.0",
         "D20220815T072044_IFCB151",
         "4.6007",
         "Surface",
         null,
         null,
         "D20220815T072044_IFCB151",
         "D20220815T072044_IFCB151",
         "90.0",
         "2022-08-14",
         "2022-08-15 07:20:44",
         "2022-08-15 00:20:44",
         "1",
         "4.6007"
        ],
        [
         "4",
         "2208BH",
         "37.0",
         "33.18462",
         "-118.38708",
         "8/14/22",
         "00:52",
         "22:26",
         null,
         "9.0",
         "30.0",
         "D20220815T075238_IFCB151",
         "4.7274",
         "DCM",
         null,
         null,
         "D20220815T075238_IFCB151",
         "D20220815T075238_IFCB151",
         "90.0",
         "2022-08-14",
         "2022-08-15 07:52:38",
         "2022-08-15 00:52:38",
         "1",
         "4.7274"
        ]
       ],
       "shape": {
        "columns": 23,
        "rows": 5
       }
      },
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Cruise</th>\n",
       "      <th>Station</th>\n",
       "      <th>Latitude</th>\n",
       "      <th>Longitude</th>\n",
       "      <th>Cast_Date</th>\n",
       "      <th>Cast_Time</th>\n",
       "      <th>Cast_Time_logged</th>\n",
       "      <th>Cast</th>\n",
       "      <th>Bottle</th>\n",
       "      <th>Depth</th>\n",
       "      <th>Filename</th>\n",
       "      <th>ml_analyzed</th>\n",
       "      <th>Depthstype</th>\n",
       "      <th>Notes</th>\n",
       "      <th>skip</th>\n",
       "      <th>filename</th>\n",
       "      <th>bin</th>\n",
       "      <th>Line</th>\n",
       "      <th>Date</th>\n",
       "      <th>Sample_time_UTC</th>\n",
       "      <th>Sample_time_PT</th>\n",
       "      <th>days_cast_to_run</th>\n",
       "      <th>Volume_ml</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>8/14/22</td>\n",
       "      <td>16:38</td>\n",
       "      <td>14:43</td>\n",
       "      <td>NaN</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>Surface</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "      <td>93.3</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>2022-08-14 23:38:43</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>0</td>\n",
       "      <td>4.5366</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>8/14/22</td>\n",
       "      <td>17:07</td>\n",
       "      <td>14:43</td>\n",
       "      <td>NaN</td>\n",
       "      <td>9.0</td>\n",
       "      <td>25.0</td>\n",
       "      <td>D20220815T000738_IFCB151</td>\n",
       "      <td>3.2233</td>\n",
       "      <td>DCM</td>\n",
       "      <td>Chl Max @ 25m</td>\n",
       "      <td>NaN</td>\n",
       "      <td>D20220815T000738_IFCB151</td>\n",
       "      <td>D20220815T000738_IFCB151</td>\n",
       "      <td>93.3</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>2022-08-15 00:07:38</td>\n",
       "      <td>2022-08-14 17:07:38</td>\n",
       "      <td>0</td>\n",
       "      <td>3.2233</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>30.0</td>\n",
       "      <td>32.84637</td>\n",
       "      <td>-117.53122</td>\n",
       "      <td>8/14/22</td>\n",
       "      <td>18:31</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>9.0</td>\n",
       "      <td>35.0</td>\n",
       "      <td>D20220815T013156_IFCB151</td>\n",
       "      <td>3.7947</td>\n",
       "      <td>DCM</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>D20220815T013156_IFCB151</td>\n",
       "      <td>D20220815T013156_IFCB151</td>\n",
       "      <td>93.3</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>2022-08-15 01:31:56</td>\n",
       "      <td>2022-08-14 18:31:56</td>\n",
       "      <td>0</td>\n",
       "      <td>3.7947</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>37.0</td>\n",
       "      <td>33.18462</td>\n",
       "      <td>-118.38708</td>\n",
       "      <td>8/14/22</td>\n",
       "      <td>00:20</td>\n",
       "      <td>22:26</td>\n",
       "      <td>NaN</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>D20220815T072044_IFCB151</td>\n",
       "      <td>4.6007</td>\n",
       "      <td>Surface</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>D20220815T072044_IFCB151</td>\n",
       "      <td>D20220815T072044_IFCB151</td>\n",
       "      <td>90.0</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>2022-08-15 07:20:44</td>\n",
       "      <td>2022-08-15 00:20:44</td>\n",
       "      <td>1</td>\n",
       "      <td>4.6007</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>37.0</td>\n",
       "      <td>33.18462</td>\n",
       "      <td>-118.38708</td>\n",
       "      <td>8/14/22</td>\n",
       "      <td>00:52</td>\n",
       "      <td>22:26</td>\n",
       "      <td>NaN</td>\n",
       "      <td>9.0</td>\n",
       "      <td>30.0</td>\n",
       "      <td>D20220815T075238_IFCB151</td>\n",
       "      <td>4.7274</td>\n",
       "      <td>DCM</td>\n",
       "      <td>NaN</td>\n",
       "      <td>NaN</td>\n",
       "      <td>D20220815T075238_IFCB151</td>\n",
       "      <td>D20220815T075238_IFCB151</td>\n",
       "      <td>90.0</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>2022-08-15 07:52:38</td>\n",
       "      <td>2022-08-15 00:52:38</td>\n",
       "      <td>1</td>\n",
       "      <td>4.7274</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Cruise  Station  Latitude  Longitude Cast_Date Cast_Time Cast_Time_logged  Cast  Bottle  Depth                  Filename  ml_analyzed Depthstype          Notes skip                  filename  \\\n",
       "0  2208BH     28.0  32.91304 -117.39438   8/14/22     16:38            14:43   NaN    11.0   10.0  D20220814T233843_IFCB151       4.5366    Surface            NaN  NaN  D20220814T233843_IFCB151   \n",
       "1  2208BH     28.0  32.91304 -117.39438   8/14/22     17:07            14:43   NaN     9.0   25.0  D20220815T000738_IFCB151       3.2233        DCM  Chl Max @ 25m  NaN  D20220815T000738_IFCB151   \n",
       "2  2208BH     30.0  32.84637 -117.53122   8/14/22     18:31              NaN   NaN     9.0   35.0  D20220815T013156_IFCB151       3.7947        DCM            NaN  NaN  D20220815T013156_IFCB151   \n",
       "3  2208BH     37.0  33.18462 -118.38708   8/14/22     00:20            22:26   NaN    11.0   10.0  D20220815T072044_IFCB151       4.6007    Surface            NaN  NaN  D20220815T072044_IFCB151   \n",
       "4  2208BH     37.0  33.18462 -118.38708   8/14/22     00:52            22:26   NaN     9.0   30.0  D20220815T075238_IFCB151       4.7274        DCM            NaN  NaN  D20220815T075238_IFCB151   \n",
       "\n",
       "                        bin  Line        Date     Sample_time_UTC      Sample_time_PT  days_cast_to_run  Volume_ml  \n",
       "0  D20220814T233843_IFCB151  93.3  2022-08-14 2022-08-14 23:38:43 2022-08-14 16:38:43                 0     4.5366  \n",
       "1  D20220815T000738_IFCB151  93.3  2022-08-14 2022-08-15 00:07:38 2022-08-14 17:07:38                 0     3.2233  \n",
       "2  D20220815T013156_IFCB151  93.3  2022-08-14 2022-08-15 01:31:56 2022-08-14 18:31:56                 0     3.7947  \n",
       "3  D20220815T072044_IFCB151  90.0  2022-08-14 2022-08-15 07:20:44 2022-08-15 00:20:44                 1     4.6007  \n",
       "4  D20220815T075238_IFCB151  90.0  2022-08-14 2022-08-15 07:52:38 2022-08-15 00:52:38                 1     4.7274  "
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "meta = read_table(METADATA_FILE)\n",
    "meta.columns = meta.columns.str.strip()\n",
    "meta = meta.loc[:, ~meta.columns.str.startswith(\"Unnamed\")]   # stray index column saved in the csv\n",
    "meta = meta.rename(columns={\"sample_type\": \"Depthstype\", \"Cast_Time (PT)\": \"Cast_Time\"})\n",
    "\n",
    "meta[\"filename\"] = meta[\"Filename\"].astype(\"string\").str.strip()\n",
    "meta[\"bin\"] = meta[\"filename\"].map(bin_id)\n",
    "\n",
    "# 'skip' column ('yes' / TRUE) -> drop every row of that bin\n",
    "is_skip = (meta[\"skip\"].astype(str).str.strip().str.lower().isin([\"true\", \"yes\", \"y\", \"1\"])\n",
    "           if \"skip\" in meta else pd.Series(False, index=meta.index))\n",
    "skip_bins = set(meta.loc[is_skip, \"bin\"].dropna())\n",
    "if skip_bins:\n",
    "    print(f\"! {len(skip_bins)} bin(s) flagged skip (dropped): {sorted(skip_bins)}\")\n",
    "    clash = meta[~is_skip & meta[\"bin\"].isin(skip_bins)]\n",
    "    if len(clash):\n",
    "        print(\"  ! these skip bins ALSO have a full metadata row - check which is right:\")\n",
    "        display(clash[[\"filename\", \"Cruise\", \"Station\", \"Cast_Date\", \"Depth\", \"Depthstype\", \"Notes\"]])\n",
    "meta = meta[~is_skip & ~meta[\"bin\"].isin(skip_bins)].copy()\n",
    "\n",
    "bad_names = meta[meta[\"bin\"].isna() | (meta[\"bin\"] != meta[\"filename\"])]\n",
    "if len(bad_names):\n",
    "    print(f\"! {len(bad_names)} metadata row(s) with a missing/malformed filename (skipped):\")\n",
    "    display(bad_names[[\"filename\", \"Cruise\", \"Station\", \"Cast_Date\", \"Depth\", \"Depthstype\"]])\n",
    "meta = meta[meta[\"bin\"].notna() & (meta[\"bin\"] == meta[\"filename\"])].copy()\n",
    "\n",
    "dups = meta[meta[\"bin\"].duplicated(keep=False)]\n",
    "if len(dups):\n",
    "    print(f\"! duplicated filenames in metadata (first kept):\")\n",
    "    display(dups)\n",
    "meta = meta.drop_duplicates(\"bin\", keep=\"first\")\n",
    "\n",
    "# 'Station' holds \"line station\", e.g. \"93.3 28.0\" or \"90 120\"\n",
    "ls = meta[\"Station\"].astype(\"string\").str.split(n=1, expand=True).reindex(columns=[0, 1])\n",
    "meta[\"Line\"] = pd.to_numeric(ls[0], errors=\"coerce\")\n",
    "meta[\"Station\"] = pd.to_numeric(ls[1], errors=\"coerce\")\n",
    "\n",
    "for col in [\"Latitude\", \"Longitude\", \"Depth\", \"Bottle\", \"Cast\"]:\n",
    "    if col in meta:\n",
    "        meta[col] = pd.to_numeric(meta[col], errors=\"coerce\")\n",
    "\n",
    "# Bin timestamp is UTC -> San Diego local time (America/Los_Angeles: PST in winter, PDT in summer).\n",
    "# Stored tz-naive so it can be written to Excel.\n",
    "meta[\"Date\"] = pd.to_datetime(meta[\"Cast_Date\"], format=\"%m/%d/%y\", errors=\"coerce\")   # actual cast date (local)\n",
    "meta[\"Sample_time_UTC\"] = pd.to_datetime(meta[\"bin\"].str[1:16], format=\"%Y%m%dT%H%M%S\")\n",
    "meta[\"Sample_time_PT\"] = (meta[\"Sample_time_UTC\"].dt.tz_localize(\"UTC\")\n",
    "                          .dt.tz_convert(\"America/Los_Angeles\").dt.tz_localize(None))\n",
    "\n",
    "# Cast_Time = sample time in PT (HH:MM); the hand-logged value is kept for reference\n",
    "# (already a column in the csv; created here only for an older file)\n",
    "if \"Cast_Time_logged\" not in meta:\n",
    "    meta[\"Cast_Time_logged\"] = meta[\"Cast_Time\"]\n",
    "meta[\"Cast_Time\"] = meta[\"Sample_time_PT\"].dt.strftime(\"%H:%M\")\n",
    "\n",
    "# The IFCB run should be on the cast date (local). A late-evening cast can run just after\n",
    "# midnight, so next day before LATE_RUN_HOUR is fine; anything else is probably a Cast_Date typo.\n",
    "LATE_RUN_HOUR = 6\n",
    "meta[\"days_cast_to_run\"] = (meta[\"Sample_time_PT\"].dt.normalize() - meta[\"Date\"]).dt.days\n",
    "ok = (meta[\"days_cast_to_run\"] == 0) | ((meta[\"days_cast_to_run\"] == 1) & (meta[\"Sample_time_PT\"].dt.hour < LATE_RUN_HOUR))\n",
    "odd = meta[~ok]\n",
    "if len(odd):\n",
    "    print(f\"! {len(odd)} row(s) where Cast_Date doesn't fit the local sample time (typo?):\")\n",
    "    display(odd[[\"filename\", \"Cruise\", \"Line\", \"Station\", \"Cast_Date\", \"Cast_Time_logged\", \"Sample_time_PT\", \"days_cast_to_run\"]])\n",
    "meta[\"Date\"] = meta[\"Date\"].dt.date\n",
    "\n",
    "if DEPTHTYPE_MAP and \"Depthstype\" in meta:\n",
    "    m = {norm_name(k): v for k, v in DEPTHTYPE_MAP.items()}   # 'Chl_Max', 'Chl Max', 'chl max' all match\n",
    "    meta[\"Depthstype\"] = meta[\"Depthstype\"].map(lambda x: m.get(norm_name(x), str(x).strip()) if pd.notna(x) else x)\n",
    "\n",
    "# Volume analyzed: 'ml_analyzed' in the csv; blanks filled from the .hdr files (step above)\n",
    "vol_ml = vol.loc[~vol.index.duplicated(), \"ml_analyzed\"]\n",
    "meta[\"Volume_ml\"] = (pd.to_numeric(meta[\"ml_analyzed\"], errors=\"coerce\") if \"ml_analyzed\" in meta\n",
    "                     else pd.Series(np.nan, index=meta.index))\n",
    "meta[\"Volume_ml\"] = meta[\"Volume_ml\"].fillna(meta[\"bin\"].map(vol_ml))\n",
    "\n",
    "print(f\"Metadata: {len(meta)} valid IFCB files\")\n",
    "print(\"Depthstype:\", meta[\"Depthstype\"].value_counts(dropna=False).to_dict())\n",
    "for col in [\"Volume_ml\", \"Depth\", \"Latitude\", \"Longitude\", \"Cruise\", \"Date\"]:\n",
    "    if col in meta:\n",
    "        n = meta[col].isna().sum()\n",
    "        if n: print(f\"  - {col}: {n} missing\")\n",
    "meta.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee5dbc63",
   "metadata": {},
   "source": [
    "## 4. Pair feature and autoclass files"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "46dae8da",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Indexing feature files...\n",
      "Indexing autoclass files...\n",
      "\n",
      "Feature files: 684 | Autoclass files: 684 | paired: 684\n",
      "  ! paired but NOT in metadata (12) -> skipped: ['D20220815T170722_IFCB151', 'D20220818T163206_IFCB151', 'D20220819T155919_IFCB151', 'D20220829T044632_IFCB151', 'D20221015T235134_IFCB151', 'D20221111T035943_IFCB151', 'D20250326T203425_IFCB151', 'D20250329T003124_IFCB151', 'D20250329T123044_IFCB151', 'D20250330T045049_IFCB151']\n",
      "\n",
      "Bins to process: 672\n"
     ]
    }
   ],
   "source": [
    "print(\"Indexing feature files...\")\n",
    "feat_files = index_folder(FEATURE_DIR, FEATURE_GLOB)\n",
    "print(\"Indexing autoclass files...\")\n",
    "class_files = index_folder(CLASS_DIR, CLASS_GLOB)\n",
    "\n",
    "both = sorted(set(feat_files) & set(class_files))\n",
    "only_feat  = sorted(set(feat_files) - set(class_files))\n",
    "only_class = sorted(set(class_files) - set(feat_files))\n",
    "no_meta    = sorted(set(both) - set(meta[\"bin\"]))\n",
    "meta_no_data = sorted(set(meta[\"bin\"]) - set(both))\n",
    "\n",
    "print(f\"\\nFeature files: {len(feat_files)} | Autoclass files: {len(class_files)} | paired: {len(both)}\")\n",
    "if only_feat:    print(f\"  ! features but no autoclass ({len(only_feat)}): {only_feat[:10]}\")\n",
    "if only_class:   print(f\"  ! autoclass but no features ({len(only_class)}): {only_class[:10]}\")\n",
    "if no_meta:      print(f\"  ! paired but NOT in metadata ({len(no_meta)}) -> skipped: {no_meta[:10]}\")\n",
    "if meta_no_data: print(f\"  - in metadata but no data files ({len(meta_no_data)}): {meta_no_data[:10]}\")\n",
    "\n",
    "bins_to_run = [b for b in both if b in set(meta[\"bin\"])]\n",
    "print(f\"\\nBins to process: {len(bins_to_run)}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2aafa2bf",
   "metadata": {},
   "source": [
    "## 5. WoRMS match table\n",
    "\n",
    "Every autoclass class name is matched to `ScientificName (IFCB)` after normalising case, `_`, `-` and spaces\n",
    "(so `pennate_Pseudo-nitzschia` matches `pennate Pseudo nitzschia`). Unmatched classes are listed —\n",
    "add them to the match file and re-run this cell if you want them mapped."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "d1cbc036",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Autoclass files (class_changed): {'topN': 672}\n",
      "131 autoclass classes | exact: 126 | tag-fallback: 5 | unmatched: 0\n",
      "  (top-N files: only classes that appear in some ROI's top-N are listed)\n",
      "\n",
      "TAG fallback matches:\n",
      "  Chaetoceros_TAG_interaction -> Chaetoceros\n",
      "  Bacteriastrum_TAG_interaction -> Bacteriastrum\n",
      "  Dinophyceae_TAG_cyst -> Dinophyceae\n",
      "  Amoeba_TAG_nano -> Amoeba\n",
      "  Lingulodinium_polyedra_TAG_cyst -> Lingulodinium_polyedra\n"
     ]
    }
   ],
   "source": [
    "worms = read_table(WORMS_FILE)\n",
    "worms.columns = worms.columns.str.strip()\n",
    "worms[\"key\"] = worms[\"ScientificName (IFCB)\"].map(norm_name)\n",
    "worms = worms.drop_duplicates(\"key\")\n",
    "worms_by_key = worms.set_index(\"key\")\n",
    "\n",
    "TAXON_COLS = [\"WoRMS matched name\", \"AphiaID\", \"WoRMS Status\", \"Cell (yes/no)\",\n",
    "              \"Kingdom\", \"Phylum\", \"Class\", \"Order\", \"Family\", \"Genus\", \"Species\"]\n",
    "TAXON_COLS = [c for c in TAXON_COLS if c in worms.columns]\n",
    "\n",
    "# Two autoclass file formats are supported (detected per file from the header):\n",
    "#   \"scores\": pid + one score column per class                         (*_class_scores.csv)\n",
    "#   \"topN\":   pid, top_class, top_score, class2..N, score2..N           (*_class_changed.csv, made in step 4)\n",
    "TOPN_LABEL_RE = re.compile(r\"top_class|class\\d+\")\n",
    "\n",
    "def class_format(cols):\n",
    "    return \"topN\" if {\"top_class\", \"top_score\"} <= set(cols) else \"scores\"\n",
    "\n",
    "headers = {b: tuple(pd.read_csv(class_files[b], nrows=0).columns) for b in bins_to_run}\n",
    "formats = {b: class_format(h) for b, h in headers.items()}\n",
    "print(f\"Autoclass files ({CLASS_DIR}):\", pd.Series(formats).value_counts().to_dict())\n",
    "\n",
    "# Every file should share one header; list any that differ from the most common one\n",
    "ref_header = pd.Series(headers).value_counts().index[0]\n",
    "odd_header = [b for b, h in headers.items() if h != ref_header]\n",
    "if odd_header:\n",
    "    print(f\"! {len(odd_header)} file(s) with a different header from the rest: {odd_header[:10]}\")\n",
    "\n",
    "# Class names = union across all files (score-column headers, or the labels in a top-N file)\n",
    "class_names = {}\n",
    "for b in bins_to_run:\n",
    "    if formats[b] == \"scores\":\n",
    "        class_names.update(dict.fromkeys(headers[b][1:]))\n",
    "    else:\n",
    "        lab = pd.read_csv(class_files[b], usecols=lambda c: bool(TOPN_LABEL_RE.fullmatch(c)))\n",
    "        class_names.update(dict.fromkeys(pd.unique(lab.to_numpy().ravel())))\n",
    "class_names = [c for c in class_names if pd.notna(c)]\n",
    "\n",
    "# Sanity check: no header names / numbers should have slipped in as class names\n",
    "bad = [c for c in class_names if c in (\"pid\", \"top_class\", \"top_score\") or re.fullmatch(r\"(class|score)\\d+\", str(c))\n",
    "       or pd.notna(pd.to_numeric(c, errors=\"coerce\"))]\n",
    "if bad:\n",
    "    raise ValueError(f\"Class files not read correctly - header/numeric values taken as classes: {bad[:10]}\")\n",
    "\n",
    "rows, fallback, unmatched = [], [], []\n",
    "for c in class_names:\n",
    "    k = norm_name(c)\n",
    "    how = \"exact\"\n",
    "    if k not in worms_by_key.index and TAG_FALLBACK and \"_TAG_\" in c:\n",
    "        k2 = norm_name(c.split(\"_TAG_\")[0])\n",
    "        if k2 in worms_by_key.index:\n",
    "            k, how = k2, \"tag-fallback\"\n",
    "            fallback.append(f\"{c} -> {worms_by_key.loc[k, 'ScientificName (IFCB)']}\")\n",
    "    if k in worms_by_key.index:\n",
    "        r = worms_by_key.loc[k, TAXON_COLS].to_dict()\n",
    "    else:\n",
    "        r, how = {col: np.nan for col in TAXON_COLS}, \"UNMATCHED\"\n",
    "        unmatched.append(c)\n",
    "    rows.append({\"Taxa\": c, \"match\": how, **r})\n",
    "\n",
    "class_map = pd.DataFrame(rows).set_index(\"Taxa\")\n",
    "print(f\"{len(class_names)} autoclass classes | exact: {(class_map.match=='exact').sum()} \"\n",
    "      f\"| tag-fallback: {len(fallback)} | unmatched: {len(unmatched)}\")\n",
    "if any(f == \"topN\" for f in formats.values()):\n",
    "    print(\"  (top-N files: only classes that appear in some ROI's top-N are listed)\")\n",
    "if fallback:  print(\"\\nTAG fallback matches:\\n  \" + \"\\n  \".join(fallback))\n",
    "if unmatched: print(\"\\n! Not in WoRMS match file (WoRMS columns will be blank):\\n  \" + \"\\n  \".join(unmatched))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "04d20bce",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "In WoRMS file but not in autoclass output: []\n"
     ]
    }
   ],
   "source": [
    "# Classes the match file lists but the classifier doesn't output (usually just naming drift — worth a look)\n",
    "unused = sorted(set(worms[\"key\"]) - {norm_name(c) for c in class_names}\n",
    "                - {norm_name(c.split(\"_TAG_\")[0]) for c in class_names})\n",
    "print(\"In WoRMS file but not in autoclass output:\", [worms_by_key.loc[k, \"ScientificName (IFCB)\"] for k in unused])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4847c328",
   "metadata": {},
   "source": [
    "## 6. Assign classes and join features\n",
    "\n",
    "For each bin: top-scoring class per ROI (`pid …_00002` → `roi_number 2`), joined to `EquivDiameter` and `Biovolume`\n",
    "from the feature file, converted from pixels to µm / µm³, and put into ESD size bins."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "abe5c3e2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  processed 50/672 bins\n",
      "  processed 100/672 bins\n",
      "  processed 150/672 bins\n",
      "  processed 200/672 bins\n",
      "  processed 250/672 bins\n",
      "  processed 300/672 bins\n",
      "  processed 350/672 bins\n",
      "  processed 400/672 bins\n",
      "  processed 450/672 bins\n",
      "  processed 500/672 bins\n",
      "  processed 550/672 bins\n",
      "  processed 600/672 bins\n",
      "  processed 650/672 bins\n",
      "  processed 672/672 bins\n",
      "\n",
      "ROIs classified + measured: 876,598\n"
     ]
    },
    {
     "data": {
      "application/vnd.microsoft.datawrangler.viewer.v0+json": {
       "columns": [
        {
         "name": "index",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "bin",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "roi_number",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "Taxa",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "score",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Biovolume",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "EquivDiameter",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "ESD_um",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Biovolume_um3",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Sizerange ESD",
         "rawType": "category",
         "type": "unknown"
        }
       ],
       "ref": "589e16cd-afbd-44ec-bcea-7829cfc5ffd5",
       "rows": [
        [
         "0",
         "D20220814T233843_IFCB151",
         "1",
         "Cerataulina_pelagica",
         "0.537",
         "32586.48763",
         "47.432207",
         "13.950649117647059",
         "829.0883276511297",
         "10-20"
        ],
        [
         "1",
         "D20220814T233843_IFCB151",
         "2",
         "detritus",
         "0.596",
         "3379.347475",
         "23.262132",
         "6.841803529411766",
         "85.97973425096683",
         "<10"
        ],
        [
         "2",
         "D20220814T233843_IFCB151",
         "3",
         "detritus_transparent",
         "0.9683",
         "12484.644423",
         "35.413853",
         "10.41583911764706",
         "317.6431005241197",
         "10-20"
        ],
        [
         "3",
         "D20220814T233843_IFCB151",
         "4",
         "Chaetoceros",
         "0.919",
         "19826.818089",
         "39.894228",
         "11.733596470588235",
         "504.44784472318344",
         "10-20"
        ],
        [
         "4",
         "D20220814T233843_IFCB151",
         "5",
         "detritus",
         "0.3425",
         "20171.246102",
         "43.992319",
         "12.938917352941177",
         "513.2110243741096",
         "10-20"
        ]
       ],
       "shape": {
        "columns": 9,
        "rows": 5
       }
      },
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>bin</th>\n",
       "      <th>roi_number</th>\n",
       "      <th>Taxa</th>\n",
       "      <th>score</th>\n",
       "      <th>Biovolume</th>\n",
       "      <th>EquivDiameter</th>\n",
       "      <th>ESD_um</th>\n",
       "      <th>Biovolume_um3</th>\n",
       "      <th>Sizerange ESD</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "      <td>1</td>\n",
       "      <td>Cerataulina_pelagica</td>\n",
       "      <td>0.5370</td>\n",
       "      <td>32586.487630</td>\n",
       "      <td>47.432207</td>\n",
       "      <td>13.950649</td>\n",
       "      <td>829.088328</td>\n",
       "      <td>10-20</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "      <td>2</td>\n",
       "      <td>detritus</td>\n",
       "      <td>0.5960</td>\n",
       "      <td>3379.347475</td>\n",
       "      <td>23.262132</td>\n",
       "      <td>6.841804</td>\n",
       "      <td>85.979734</td>\n",
       "      <td>&lt;10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "      <td>3</td>\n",
       "      <td>detritus_transparent</td>\n",
       "      <td>0.9683</td>\n",
       "      <td>12484.644423</td>\n",
       "      <td>35.413853</td>\n",
       "      <td>10.415839</td>\n",
       "      <td>317.643101</td>\n",
       "      <td>10-20</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "      <td>4</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>0.9190</td>\n",
       "      <td>19826.818089</td>\n",
       "      <td>39.894228</td>\n",
       "      <td>11.733596</td>\n",
       "      <td>504.447845</td>\n",
       "      <td>10-20</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "      <td>5</td>\n",
       "      <td>detritus</td>\n",
       "      <td>0.3425</td>\n",
       "      <td>20171.246102</td>\n",
       "      <td>43.992319</td>\n",
       "      <td>12.938917</td>\n",
       "      <td>513.211024</td>\n",
       "      <td>10-20</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                        bin  roi_number                  Taxa   score     Biovolume  EquivDiameter     ESD_um  Biovolume_um3 Sizerange ESD\n",
       "0  D20220814T233843_IFCB151           1  Cerataulina_pelagica  0.5370  32586.487630      47.432207  13.950649     829.088328         10-20\n",
       "1  D20220814T233843_IFCB151           2              detritus  0.5960   3379.347475      23.262132   6.841804      85.979734           <10\n",
       "2  D20220814T233843_IFCB151           3  detritus_transparent  0.9683  12484.644423      35.413853  10.415839     317.643101         10-20\n",
       "3  D20220814T233843_IFCB151           4           Chaetoceros  0.9190  19826.818089      39.894228  11.733596     504.447845         10-20\n",
       "4  D20220814T233843_IFCB151           5              detritus  0.3425  20171.246102      43.992319  12.938917     513.211024         10-20"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "FEATURE_COLS = [\"roi_number\", \"EquivDiameter\", \"Biovolume\"]\n",
    "\n",
    "def process_bin(b):\n",
    "    cls = pd.read_csv(class_files[b])\n",
    "    if formats[b] == \"topN\":\n",
    "        taxa, score = cls[\"top_class\"], pd.to_numeric(cls[\"top_score\"], errors=\"coerce\")\n",
    "    else:\n",
    "        scores = cls.iloc[:, 1:].apply(pd.to_numeric, errors=\"coerce\")\n",
    "        taxa, score = scores.idxmax(axis=1), scores.max(axis=1)\n",
    "    out = pd.DataFrame({\n",
    "        \"bin\": b,\n",
    "        \"roi_number\": cls.iloc[:, 0].astype(str).str.rsplit(\"_\", n=1).str[-1].astype(int),\n",
    "        \"Taxa\": taxa,\n",
    "        \"score\": score,\n",
    "    })\n",
    "    if MIN_CONFIDENCE is not None:\n",
    "        out.loc[out[\"score\"] < MIN_CONFIDENCE, \"Taxa\"] = \"unclassified\"\n",
    "\n",
    "    feat = pd.read_csv(feature_files_lookup[b], usecols=lambda c: c in FEATURE_COLS)\n",
    "    feat[\"roi_number\"] = feat[\"roi_number\"].astype(int)\n",
    "    merged = out.merge(feat, on=\"roi_number\", how=\"outer\", indicator=True)\n",
    "    n_cls_only  = (merged[\"_merge\"] == \"left_only\").sum()\n",
    "    n_feat_only = (merged[\"_merge\"] == \"right_only\").sum()\n",
    "    merged = merged[merged[\"_merge\"] == \"both\"].drop(columns=\"_merge\")\n",
    "    return merged, n_cls_only, n_feat_only\n",
    "\n",
    "feature_files_lookup = feat_files\n",
    "parts, mismatch = [], []\n",
    "for i, b in enumerate(bins_to_run, 1):\n",
    "    df, a, f = process_bin(b)\n",
    "    parts.append(df)\n",
    "    if a or f:\n",
    "        mismatch.append((b, a, f))\n",
    "    if i % 50 == 0 or i == len(bins_to_run):\n",
    "        print(f\"  processed {i}/{len(bins_to_run)} bins\")\n",
    "\n",
    "roi = pd.concat(parts, ignore_index=True)\n",
    "\n",
    "# pixel -> micron\n",
    "roi[\"ESD_um\"]       = roi[\"EquivDiameter\"] / PIXELS_PER_MICRON\n",
    "roi[\"Biovolume_um3\"] = roi[\"Biovolume\"] / PIXELS_PER_MICRON**3\n",
    "roi[\"Sizerange ESD\"] = pd.cut(roi[\"ESD_um\"], bins=SIZE_BIN_EDGES, labels=SIZE_BIN_LABELS, right=False)\n",
    "\n",
    "print(f\"\\nROIs classified + measured: {len(roi):,}\")\n",
    "unknown = set(roi[\"Taxa\"].dropna()) - set(class_map.index) - {\"unclassified\"}\n",
    "if unknown:\n",
    "    print(f\"! assigned classes missing from class_map (re-run step 5): {sorted(unknown)}\")\n",
    "if mismatch:\n",
    "    print(f\"! {len(mismatch)} bin(s) where class and feature ROIs don't line up (bin, class-only, feature-only):\")\n",
    "    for m in mismatch[:10]: print(\"   \", m)\n",
    "roi.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b098e4db",
   "metadata": {},
   "source": [
    "## 7. Filter taxa"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "c5d54953",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Excluded classes (12): ['Bacteria_colony', 'bad', 'bead', 'bubble', 'crescent', 'detritus', 'detritus_theca_fragment', 'detritus_transparent', 'fecal_pellet', 'fiber', 'pollen', 'pollen_TAG_nano']\n",
      "ROIs kept: 530,927 of 876,598 (345,671 removed)\n",
      "\n",
      "Removed ROI counts by class:\n",
      "Taxa\n",
      "detritus_transparent       155063\n",
      "bead                        89384\n",
      "detritus                    78723\n",
      "bubble                      16992\n",
      "fiber                        2746\n",
      "detritus_theca_fragment      1263\n",
      "Bacteria_colony               801\n",
      "pollen_TAG_nano               361\n",
      "bad                           186\n",
      "fecal_pellet                  126\n",
      "crescent                       20\n",
      "pollen                          6\n"
     ]
    }
   ],
   "source": [
    "drop = set(EXCLUDE_TAXA)\n",
    "if EXCLUDE_WORMS_EXCLUDED and \"WoRMS Status\" in class_map:\n",
    "    drop |= set(class_map.index[class_map[\"WoRMS Status\"].astype(str).str.lower().eq(\"excluded\")])\n",
    "if EXCLUDE_NON_CELLS and \"Cell (yes/no)\" in class_map:\n",
    "    drop |= set(class_map.index[class_map[\"Cell (yes/no)\"].astype(str).str.lower().eq(\"no\")])\n",
    "if MIN_CONFIDENCE is not None:\n",
    "    drop.add(\"unclassified\")\n",
    "\n",
    "before = roi[\"Taxa\"].value_counts()\n",
    "roi_f = roi[~roi[\"Taxa\"].isin(drop)]\n",
    "if KEEP_ONLY_TAXA is not None:\n",
    "    roi_f = roi_f[roi_f[\"Taxa\"].isin(KEEP_ONLY_TAXA)]\n",
    "roi_f = roi_f.copy()\n",
    "\n",
    "removed = before[before.index.isin(set(before.index) - set(roi_f[\"Taxa\"]))]\n",
    "print(f\"Excluded classes ({len(drop)}): {sorted(drop)}\")\n",
    "print(f\"ROIs kept: {len(roi_f):,} of {len(roi):,} ({len(roi) - len(roi_f):,} removed)\")\n",
    "print(\"\\nRemoved ROI counts by class:\")\n",
    "print(removed.to_string() if len(removed) else \"  none\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7dff6f24",
   "metadata": {},
   "source": [
    "## 8. Aggregate into the summary\n",
    "\n",
    "Per IFCB file × taxon × size bin: ROI count, abundance (count / ml analyzed), mean & SD of biovolume (µm³) and ESD (µm)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "6b0b832f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Summary rows: 29,686  | bins: 671  | taxa: 104\n"
     ]
    }
   ],
   "source": [
    "# Attach WoRMS info to each ROI\n",
    "# (drop first so re-running this cell doesn't try to add the WoRMS columns twice)\n",
    "roi_f = roi_f.drop(columns=TAXON_COLS, errors=\"ignore\").join(class_map[TAXON_COLS], on=\"Taxa\")\n",
    "\n",
    "if GROUP_BY == \"worms\":\n",
    "    # merge classes that share a WoRMS name; unmatched classes keep their own name\n",
    "    roi_f[\"group\"] = roi_f[\"WoRMS matched name\"].fillna(roi_f[\"Taxa\"])\n",
    "    roi_f[\"Taxa_merged\"] = roi_f.groupby(\"group\")[\"Taxa\"].transform(lambda s: \"; \".join(sorted(s.unique())))\n",
    "    key = \"group\"\n",
    "else:\n",
    "    key = \"Taxa\"\n",
    "\n",
    "g = roi_f.groupby([\"bin\", key, \"Sizerange ESD\"], observed=True)\n",
    "summary = g.agg(\n",
    "    Count=(\"roi_number\", \"size\"),\n",
    "    **{\"Avg Biovol\": (\"Biovolume_um3\", \"mean\"),\n",
    "       \"SD biovol\":  (\"Biovolume_um3\", lambda x: x.std(ddof=SD_DDOF)),\n",
    "       \"Avg ESD\":    (\"ESD_um\", \"mean\"),\n",
    "       \"SD ESD\":     (\"ESD_um\", lambda x: x.std(ddof=SD_DDOF))},\n",
    ").reset_index()\n",
    "summary[[\"SD biovol\", \"SD ESD\"]] = summary[[\"SD biovol\", \"SD ESD\"]].fillna(0)\n",
    "\n",
    "# taxon-level info (first row per taxon is fine — it's constant within the group)\n",
    "first_cols = TAXON_COLS + ([\"Taxa_merged\"] if GROUP_BY == \"worms\" else [])\n",
    "tax_info = roi_f.groupby(key)[first_cols].first()\n",
    "summary = summary.join(tax_info, on=key)\n",
    "if GROUP_BY == \"worms\":\n",
    "    summary = summary.rename(columns={\"group\": \"Taxa\", \"Taxa_merged\": \"Autoclass classes\"})\n",
    "\n",
    "# Metadata + abundance\n",
    "summary = summary.merge(meta, on=\"bin\", how=\"left\")\n",
    "summary[\"Abundance (counts/ml)\"] = summary[\"Count\"] / summary[\"Volume_ml\"]\n",
    "\n",
    "# Autoclass version / accuracy\n",
    "summary[\"Autoclass Version\"] = AUTOCLASS_VERSION\n",
    "if ACCURACY_FILE is not None:\n",
    "    acc = read_table(ACCURACY_FILE)\n",
    "    acc = acc[[ACCURACY_CLASS_COL, ACCURACY_VALUE_COL]].dropna().drop_duplicates(ACCURACY_CLASS_COL)\n",
    "    acc_map = dict(zip(acc[ACCURACY_CLASS_COL].map(norm_name), acc[ACCURACY_VALUE_COL]))\n",
    "    if GROUP_BY == \"worms\":\n",
    "        summary[\"Autoclass Accuracy\"] = summary[\"Autoclass classes\"].map(\n",
    "            lambda s: \"; \".join(str(acc_map.get(norm_name(c), \"NA\")) for c in s.split(\"; \")))\n",
    "    else:\n",
    "        summary[\"Autoclass Accuracy\"] = summary[\"Taxa\"].map(lambda t: acc_map.get(norm_name(t), np.nan))\n",
    "        miss = sorted(summary.loc[summary[\"Autoclass Accuracy\"].isna(), \"Taxa\"].unique())\n",
    "        if miss: print(f\"! no accuracy value for: {miss}\")\n",
    "else:\n",
    "    summary[\"Autoclass Accuracy\"] = np.nan\n",
    "\n",
    "summary = summary.rename(columns={\"filename\": \"IFCB_filename\"})\n",
    "print(f\"Summary rows: {len(summary):,}  | bins: {summary['bin'].nunique()}  | taxa: {summary['Taxa'].nunique()}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "66f09b33",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.microsoft.datawrangler.viewer.v0+json": {
       "columns": [
        {
         "name": "index",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "Cruise",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Date",
         "rawType": "object",
         "type": "unknown"
        },
        {
         "name": "Cast_Time",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Line",
         "rawType": "Float64",
         "type": "float"
        },
        {
         "name": "Station",
         "rawType": "Float64",
         "type": "float"
        },
        {
         "name": "Latitude",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Longitude",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Bottle",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Depth",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Depthstype",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Taxa",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Autoclass classes",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "WoRMS matched name",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "AphiaID",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Kingdom",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Phylum",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Class",
         "rawType": "object",
         "type": "unknown"
        },
        {
         "name": "Order",
         "rawType": "object",
         "type": "unknown"
        },
        {
         "name": "Family",
         "rawType": "object",
         "type": "unknown"
        },
        {
         "name": "Genus",
         "rawType": "object",
         "type": "unknown"
        },
        {
         "name": "Species",
         "rawType": "object",
         "type": "unknown"
        },
        {
         "name": "Sizerange ESD",
         "rawType": "category",
         "type": "unknown"
        },
        {
         "name": "Count",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "Abundance (counts/ml)",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Avg Biovol",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "SD biovol",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Avg ESD",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "SD ESD",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Autoclass Version",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "Autoclass Accuracy",
         "rawType": "object",
         "type": "string"
        },
        {
         "name": "Volume_ml",
         "rawType": "float64",
         "type": "float"
        },
        {
         "name": "Sample_time_PT",
         "rawType": "datetime64[ns]",
         "type": "datetime"
        },
        {
         "name": "IFCB_filename",
         "rawType": "string",
         "type": "string"
        }
       ],
       "ref": "be3d8b21-b41d-41bc-afce-b0954d92a8b6",
       "rows": [
        [
         "0",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Amoeba",
         "Amoeba; Amoeba_TAG_nano",
         "Amoeba",
         "120533.0",
         "Protoza",
         "Amoebozoa",
         "Tubulinea",
         "Euamoebida",
         "Amoebidae",
         "Amoeba",
         null,
         "10-20",
         "1",
         "0.22042939646431248",
         "1299.804918964991",
         "0.0",
         "13.47270323529412",
         "0.0",
         "1",
         "1; 0",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "1",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Bacillariophyceae",
         "Bacillariophyceae",
         "Bacillariophyceae",
         "148899.0",
         "Chromista",
         "Heterokontophyta",
         "Bacillariophyceae",
         null,
         null,
         null,
         null,
         "10-20",
         "10",
         "2.2042939646431248",
         "878.2358759948098",
         "387.53660941405593",
         "12.321494176470589",
         "1.9478408348518013",
         "1",
         "0.94",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "2",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Bacteriastrum",
         "Bacteriastrum; Bacteriastrum_TAG_interaction",
         "Bacteriastrum",
         "149118.0",
         "Chromista",
         "Heterokontophyta",
         "Bacillariophyceae",
         "Chaetocerotanae incertae sedis",
         "Chaetocerotaceae",
         "Bacteriastrum",
         null,
         "20-40",
         "1",
         "0.22042939646431248",
         "2809.605264858539",
         "0.0",
         "23.48126911764706",
         "0.0",
         "1",
         "0.68; 0.5",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "3",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Cerataulina pelagica",
         "Cerataulina_pelagica",
         "Cerataulina pelagica",
         "149619.0",
         "Chromista",
         "Heterokontophyta",
         "Bacillariophyceae",
         "Hemiaulales",
         "Hemiaulaceae",
         "Cerataulina",
         "pelagica",
         "10-20",
         "3",
         "0.6612881893929374",
         "1192.5295577210125",
         "324.45384034020657",
         "16.053818431372548",
         "1.951944409478708",
         "1",
         "0.83",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "4",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Chaetoceros",
         "Chaetoceros; Chaetoceros_TAG_interaction",
         "Chaetoceros",
         "148985.0",
         "Chromista",
         "Heterokontophyta",
         "Bacillariophyceae",
         "Chaetocerotanae incertae sedis",
         "Chaetocerotaceae",
         "Chaetoceros",
         null,
         "<10",
         "2",
         "0.44085879292862495",
         "584.8572612456749",
         "79.71836535562383",
         "9.749209705882354",
         "0.3475018043818146",
         "1",
         "0.99; 0.66",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "5",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Chaetoceros",
         "Chaetoceros; Chaetoceros_TAG_interaction",
         "Chaetoceros",
         "148985.0",
         "Chromista",
         "Heterokontophyta",
         "Bacillariophyceae",
         "Chaetocerotanae incertae sedis",
         "Chaetocerotaceae",
         "Chaetoceros",
         null,
         "10-20",
         "99",
         "21.822510249966935",
         "1104.680294640636",
         "742.1672232171898",
         "14.963273276886513",
         "2.40254186814822",
         "1",
         "0.99; 0.66",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "6",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Chaetoceros",
         "Chaetoceros; Chaetoceros_TAG_interaction",
         "Chaetoceros",
         "148985.0",
         "Chromista",
         "Heterokontophyta",
         "Bacillariophyceae",
         "Chaetocerotanae incertae sedis",
         "Chaetocerotaceae",
         "Chaetoceros",
         null,
         "20-40",
         "16",
         "3.5268703434289996",
         "2428.623982951799",
         "1093.1456938607766",
         "23.545662040441176",
         "3.301127150693859",
         "1",
         "0.99; 0.66",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "7",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Chaetoceros",
         "Chaetoceros; Chaetoceros_TAG_interaction",
         "Chaetoceros",
         "148985.0",
         "Chromista",
         "Heterokontophyta",
         "Bacillariophyceae",
         "Chaetocerotanae incertae sedis",
         "Chaetocerotaceae",
         "Chaetoceros",
         null,
         "40>",
         "1",
         "0.22042939646431248",
         "23198.08554696723",
         "0.0",
         "51.79927705882353",
         "0.0",
         "1",
         "0.99; 0.66",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "8",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Chaetoceros didymus",
         "Chaetoceros_didymus",
         "Chaetoceros didymus",
         "149122.0",
         "Chromista",
         "Heterokontophyta",
         "Bacillariophyceae",
         "Chaetocerotanae incertae sedis",
         "Chaetocerotaceae",
         "Chaetoceros",
         "didymus",
         "10-20",
         "3",
         "0.6612881893929374",
         "938.6812140579417",
         "263.1519303794419",
         "13.436411372549019",
         "4.027887565780391",
         "1",
         "0.57",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "9",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Chaetoceros didymus",
         "Chaetoceros_didymus",
         "Chaetoceros didymus",
         "149122.0",
         "Chromista",
         "Heterokontophyta",
         "Bacillariophyceae",
         "Chaetocerotanae incertae sedis",
         "Chaetocerotaceae",
         "Chaetoceros",
         "didymus",
         "20-40",
         "1",
         "0.22042939646431248",
         "1739.0107437919808",
         "0.0",
         "20.815810294117647",
         "0.0",
         "1",
         "0.57",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "10",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Chaetoceros socialis",
         "Chaetoceros_socialis",
         "Chaetoceros socialis",
         "149123.0",
         "Chromista",
         "Heterokontophyta",
         "Bacillariophyceae",
         "Chaetocerotanae incertae sedis",
         "Chaetocerotaceae",
         "Chaetoceros",
         "socialis",
         "10-20",
         "1",
         "0.22042939646431248",
         "873.6986579483006",
         "0.0",
         "17.850498823529414",
         "0.0",
         "1",
         "0.45",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "11",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Chrysochromulina lanceolata",
         "Chrysochromulina_lanceolata",
         "Chrysochromulina lanceolata",
         "388470.0",
         "Chromista",
         "Haptophyta",
         "Coccolithophyceae",
         "Prymnesiales",
         "Chrysochromulinaceae",
         "Chrysochromulina",
         "lanceolata",
         "10-20",
         "3",
         "0.6612881893929374",
         "679.4148642716603",
         "404.4918421323224",
         "11.886907254901962",
         "0.49028902099986316",
         "1",
         "0.16",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "12",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Cryptophyta",
         "Cryptophyta",
         "Cryptophyta",
         "17638.0",
         "Chromista",
         "Cryptophyta",
         null,
         null,
         null,
         null,
         null,
         "<10",
         "1",
         "0.22042939646431248",
         "296.79351434968453",
         "0.0",
         "9.994930588235295",
         "0.0",
         "1",
         "0.834",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "13",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Dinophyceae",
         "Dinophyceae; Dinophyceae_TAG_cyst",
         "Dinophyceae",
         "19542.0",
         "Chromista",
         "Myzozoa",
         "Dinophyceae",
         null,
         null,
         null,
         null,
         "10-20",
         "1",
         "0.22042939646431248",
         "2781.1788770099743",
         "0.0",
         "17.305364411764707",
         "0.0",
         "1",
         "0.99; 0.31",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ],
        [
         "14",
         "2208BH",
         "2022-08-14",
         "16:38",
         "93.3",
         "28.0",
         "32.91304",
         "-117.39438",
         "11.0",
         "10.0",
         "Surface",
         "Dinophyceae",
         "Dinophyceae; Dinophyceae_TAG_cyst",
         "Dinophyceae",
         "19542.0",
         "Chromista",
         "Myzozoa",
         "Dinophyceae",
         null,
         null,
         null,
         null,
         "20-40",
         "1",
         "0.22042939646431248",
         "5200.338704406677",
         "0.0",
         "21.309968529411762",
         "0.0",
         "1",
         "0.99; 0.31",
         "4.5366",
         "2022-08-14 16:38:43",
         "D20220814T233843_IFCB151"
        ]
       ],
       "shape": {
        "columns": 33,
        "rows": 15
       }
      },
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Cruise</th>\n",
       "      <th>Date</th>\n",
       "      <th>Cast_Time</th>\n",
       "      <th>Line</th>\n",
       "      <th>Station</th>\n",
       "      <th>Latitude</th>\n",
       "      <th>Longitude</th>\n",
       "      <th>Bottle</th>\n",
       "      <th>Depth</th>\n",
       "      <th>Depthstype</th>\n",
       "      <th>Taxa</th>\n",
       "      <th>Autoclass classes</th>\n",
       "      <th>WoRMS matched name</th>\n",
       "      <th>AphiaID</th>\n",
       "      <th>Kingdom</th>\n",
       "      <th>Phylum</th>\n",
       "      <th>Class</th>\n",
       "      <th>Order</th>\n",
       "      <th>Family</th>\n",
       "      <th>Genus</th>\n",
       "      <th>Species</th>\n",
       "      <th>Sizerange ESD</th>\n",
       "      <th>Count</th>\n",
       "      <th>Abundance (counts/ml)</th>\n",
       "      <th>Avg Biovol</th>\n",
       "      <th>SD biovol</th>\n",
       "      <th>Avg ESD</th>\n",
       "      <th>SD ESD</th>\n",
       "      <th>Autoclass Version</th>\n",
       "      <th>Autoclass Accuracy</th>\n",
       "      <th>Volume_ml</th>\n",
       "      <th>Sample_time_PT</th>\n",
       "      <th>IFCB_filename</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Amoeba</td>\n",
       "      <td>Amoeba; Amoeba_TAG_nano</td>\n",
       "      <td>Amoeba</td>\n",
       "      <td>120533.0</td>\n",
       "      <td>Protoza</td>\n",
       "      <td>Amoebozoa</td>\n",
       "      <td>Tubulinea</td>\n",
       "      <td>Euamoebida</td>\n",
       "      <td>Amoebidae</td>\n",
       "      <td>Amoeba</td>\n",
       "      <td>None</td>\n",
       "      <td>10-20</td>\n",
       "      <td>1</td>\n",
       "      <td>0.220429</td>\n",
       "      <td>1299.804919</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>13.472703</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>1</td>\n",
       "      <td>1; 0</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>148899.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Heterokontophyta</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>10-20</td>\n",
       "      <td>10</td>\n",
       "      <td>2.204294</td>\n",
       "      <td>878.235876</td>\n",
       "      <td>387.536609</td>\n",
       "      <td>12.321494</td>\n",
       "      <td>1.947841</td>\n",
       "      <td>1</td>\n",
       "      <td>0.94</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Bacteriastrum</td>\n",
       "      <td>Bacteriastrum; Bacteriastrum_TAG_interaction</td>\n",
       "      <td>Bacteriastrum</td>\n",
       "      <td>149118.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Heterokontophyta</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>Chaetocerotanae incertae sedis</td>\n",
       "      <td>Chaetocerotaceae</td>\n",
       "      <td>Bacteriastrum</td>\n",
       "      <td>None</td>\n",
       "      <td>20-40</td>\n",
       "      <td>1</td>\n",
       "      <td>0.220429</td>\n",
       "      <td>2809.605265</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>23.481269</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>1</td>\n",
       "      <td>0.68; 0.5</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Cerataulina pelagica</td>\n",
       "      <td>Cerataulina_pelagica</td>\n",
       "      <td>Cerataulina pelagica</td>\n",
       "      <td>149619.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Heterokontophyta</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>Hemiaulales</td>\n",
       "      <td>Hemiaulaceae</td>\n",
       "      <td>Cerataulina</td>\n",
       "      <td>pelagica</td>\n",
       "      <td>10-20</td>\n",
       "      <td>3</td>\n",
       "      <td>0.661288</td>\n",
       "      <td>1192.529558</td>\n",
       "      <td>324.453840</td>\n",
       "      <td>16.053818</td>\n",
       "      <td>1.951944</td>\n",
       "      <td>1</td>\n",
       "      <td>0.83</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>Chaetoceros; Chaetoceros_TAG_interaction</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>148985.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Heterokontophyta</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>Chaetocerotanae incertae sedis</td>\n",
       "      <td>Chaetocerotaceae</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>None</td>\n",
       "      <td>&lt;10</td>\n",
       "      <td>2</td>\n",
       "      <td>0.440859</td>\n",
       "      <td>584.857261</td>\n",
       "      <td>79.718365</td>\n",
       "      <td>9.749210</td>\n",
       "      <td>0.347502</td>\n",
       "      <td>1</td>\n",
       "      <td>0.99; 0.66</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>Chaetoceros; Chaetoceros_TAG_interaction</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>148985.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Heterokontophyta</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>Chaetocerotanae incertae sedis</td>\n",
       "      <td>Chaetocerotaceae</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>None</td>\n",
       "      <td>10-20</td>\n",
       "      <td>99</td>\n",
       "      <td>21.822510</td>\n",
       "      <td>1104.680295</td>\n",
       "      <td>742.167223</td>\n",
       "      <td>14.963273</td>\n",
       "      <td>2.402542</td>\n",
       "      <td>1</td>\n",
       "      <td>0.99; 0.66</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>Chaetoceros; Chaetoceros_TAG_interaction</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>148985.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Heterokontophyta</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>Chaetocerotanae incertae sedis</td>\n",
       "      <td>Chaetocerotaceae</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>None</td>\n",
       "      <td>20-40</td>\n",
       "      <td>16</td>\n",
       "      <td>3.526870</td>\n",
       "      <td>2428.623983</td>\n",
       "      <td>1093.145694</td>\n",
       "      <td>23.545662</td>\n",
       "      <td>3.301127</td>\n",
       "      <td>1</td>\n",
       "      <td>0.99; 0.66</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>Chaetoceros; Chaetoceros_TAG_interaction</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>148985.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Heterokontophyta</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>Chaetocerotanae incertae sedis</td>\n",
       "      <td>Chaetocerotaceae</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>None</td>\n",
       "      <td>40&gt;</td>\n",
       "      <td>1</td>\n",
       "      <td>0.220429</td>\n",
       "      <td>23198.085547</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>51.799277</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>1</td>\n",
       "      <td>0.99; 0.66</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Chaetoceros didymus</td>\n",
       "      <td>Chaetoceros_didymus</td>\n",
       "      <td>Chaetoceros didymus</td>\n",
       "      <td>149122.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Heterokontophyta</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>Chaetocerotanae incertae sedis</td>\n",
       "      <td>Chaetocerotaceae</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>didymus</td>\n",
       "      <td>10-20</td>\n",
       "      <td>3</td>\n",
       "      <td>0.661288</td>\n",
       "      <td>938.681214</td>\n",
       "      <td>263.151930</td>\n",
       "      <td>13.436411</td>\n",
       "      <td>4.027888</td>\n",
       "      <td>1</td>\n",
       "      <td>0.57</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Chaetoceros didymus</td>\n",
       "      <td>Chaetoceros_didymus</td>\n",
       "      <td>Chaetoceros didymus</td>\n",
       "      <td>149122.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Heterokontophyta</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>Chaetocerotanae incertae sedis</td>\n",
       "      <td>Chaetocerotaceae</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>didymus</td>\n",
       "      <td>20-40</td>\n",
       "      <td>1</td>\n",
       "      <td>0.220429</td>\n",
       "      <td>1739.010744</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>20.815810</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>1</td>\n",
       "      <td>0.57</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Chaetoceros socialis</td>\n",
       "      <td>Chaetoceros_socialis</td>\n",
       "      <td>Chaetoceros socialis</td>\n",
       "      <td>149123.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Heterokontophyta</td>\n",
       "      <td>Bacillariophyceae</td>\n",
       "      <td>Chaetocerotanae incertae sedis</td>\n",
       "      <td>Chaetocerotaceae</td>\n",
       "      <td>Chaetoceros</td>\n",
       "      <td>socialis</td>\n",
       "      <td>10-20</td>\n",
       "      <td>1</td>\n",
       "      <td>0.220429</td>\n",
       "      <td>873.698658</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>17.850499</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>1</td>\n",
       "      <td>0.45</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Chrysochromulina lanceolata</td>\n",
       "      <td>Chrysochromulina_lanceolata</td>\n",
       "      <td>Chrysochromulina lanceolata</td>\n",
       "      <td>388470.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Haptophyta</td>\n",
       "      <td>Coccolithophyceae</td>\n",
       "      <td>Prymnesiales</td>\n",
       "      <td>Chrysochromulinaceae</td>\n",
       "      <td>Chrysochromulina</td>\n",
       "      <td>lanceolata</td>\n",
       "      <td>10-20</td>\n",
       "      <td>3</td>\n",
       "      <td>0.661288</td>\n",
       "      <td>679.414864</td>\n",
       "      <td>404.491842</td>\n",
       "      <td>11.886907</td>\n",
       "      <td>0.490289</td>\n",
       "      <td>1</td>\n",
       "      <td>0.16</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Cryptophyta</td>\n",
       "      <td>Cryptophyta</td>\n",
       "      <td>Cryptophyta</td>\n",
       "      <td>17638.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Cryptophyta</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>&lt;10</td>\n",
       "      <td>1</td>\n",
       "      <td>0.220429</td>\n",
       "      <td>296.793514</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>9.994931</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>1</td>\n",
       "      <td>0.834</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Dinophyceae</td>\n",
       "      <td>Dinophyceae; Dinophyceae_TAG_cyst</td>\n",
       "      <td>Dinophyceae</td>\n",
       "      <td>19542.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Myzozoa</td>\n",
       "      <td>Dinophyceae</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>10-20</td>\n",
       "      <td>1</td>\n",
       "      <td>0.220429</td>\n",
       "      <td>2781.178877</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>17.305364</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>1</td>\n",
       "      <td>0.99; 0.31</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>2208BH</td>\n",
       "      <td>2022-08-14</td>\n",
       "      <td>16:38</td>\n",
       "      <td>93.3</td>\n",
       "      <td>28.0</td>\n",
       "      <td>32.91304</td>\n",
       "      <td>-117.39438</td>\n",
       "      <td>11.0</td>\n",
       "      <td>10.0</td>\n",
       "      <td>Surface</td>\n",
       "      <td>Dinophyceae</td>\n",
       "      <td>Dinophyceae; Dinophyceae_TAG_cyst</td>\n",
       "      <td>Dinophyceae</td>\n",
       "      <td>19542.0</td>\n",
       "      <td>Chromista</td>\n",
       "      <td>Myzozoa</td>\n",
       "      <td>Dinophyceae</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>None</td>\n",
       "      <td>20-40</td>\n",
       "      <td>1</td>\n",
       "      <td>0.220429</td>\n",
       "      <td>5200.338704</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>21.309969</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>1</td>\n",
       "      <td>0.99; 0.31</td>\n",
       "      <td>4.5366</td>\n",
       "      <td>2022-08-14 16:38:43</td>\n",
       "      <td>D20220814T233843_IFCB151</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    Cruise        Date Cast_Time  Line  Station  Latitude  Longitude  Bottle  Depth Depthstype                         Taxa                             Autoclass classes  \\\n",
       "0   2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface                       Amoeba                       Amoeba; Amoeba_TAG_nano   \n",
       "1   2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface            Bacillariophyceae                             Bacillariophyceae   \n",
       "2   2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface                Bacteriastrum  Bacteriastrum; Bacteriastrum_TAG_interaction   \n",
       "3   2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface         Cerataulina pelagica                          Cerataulina_pelagica   \n",
       "4   2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface                  Chaetoceros      Chaetoceros; Chaetoceros_TAG_interaction   \n",
       "5   2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface                  Chaetoceros      Chaetoceros; Chaetoceros_TAG_interaction   \n",
       "6   2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface                  Chaetoceros      Chaetoceros; Chaetoceros_TAG_interaction   \n",
       "7   2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface                  Chaetoceros      Chaetoceros; Chaetoceros_TAG_interaction   \n",
       "8   2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface          Chaetoceros didymus                           Chaetoceros_didymus   \n",
       "9   2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface          Chaetoceros didymus                           Chaetoceros_didymus   \n",
       "10  2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface         Chaetoceros socialis                          Chaetoceros_socialis   \n",
       "11  2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface  Chrysochromulina lanceolata                   Chrysochromulina_lanceolata   \n",
       "12  2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface                  Cryptophyta                                   Cryptophyta   \n",
       "13  2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface                  Dinophyceae             Dinophyceae; Dinophyceae_TAG_cyst   \n",
       "14  2208BH  2022-08-14     16:38  93.3     28.0  32.91304 -117.39438    11.0   10.0    Surface                  Dinophyceae             Dinophyceae; Dinophyceae_TAG_cyst   \n",
       "\n",
       "             WoRMS matched name   AphiaID    Kingdom            Phylum              Class                           Order                Family             Genus     Species Sizerange ESD  Count  \\\n",
       "0                        Amoeba  120533.0    Protoza         Amoebozoa          Tubulinea                      Euamoebida             Amoebidae            Amoeba        None         10-20      1   \n",
       "1             Bacillariophyceae  148899.0  Chromista  Heterokontophyta  Bacillariophyceae                            None                  None              None        None         10-20     10   \n",
       "2                 Bacteriastrum  149118.0  Chromista  Heterokontophyta  Bacillariophyceae  Chaetocerotanae incertae sedis      Chaetocerotaceae     Bacteriastrum        None         20-40      1   \n",
       "3          Cerataulina pelagica  149619.0  Chromista  Heterokontophyta  Bacillariophyceae                     Hemiaulales          Hemiaulaceae       Cerataulina    pelagica         10-20      3   \n",
       "4                   Chaetoceros  148985.0  Chromista  Heterokontophyta  Bacillariophyceae  Chaetocerotanae incertae sedis      Chaetocerotaceae       Chaetoceros        None           <10      2   \n",
       "5                   Chaetoceros  148985.0  Chromista  Heterokontophyta  Bacillariophyceae  Chaetocerotanae incertae sedis      Chaetocerotaceae       Chaetoceros        None         10-20     99   \n",
       "6                   Chaetoceros  148985.0  Chromista  Heterokontophyta  Bacillariophyceae  Chaetocerotanae incertae sedis      Chaetocerotaceae       Chaetoceros        None         20-40     16   \n",
       "7                   Chaetoceros  148985.0  Chromista  Heterokontophyta  Bacillariophyceae  Chaetocerotanae incertae sedis      Chaetocerotaceae       Chaetoceros        None           40>      1   \n",
       "8           Chaetoceros didymus  149122.0  Chromista  Heterokontophyta  Bacillariophyceae  Chaetocerotanae incertae sedis      Chaetocerotaceae       Chaetoceros     didymus         10-20      3   \n",
       "9           Chaetoceros didymus  149122.0  Chromista  Heterokontophyta  Bacillariophyceae  Chaetocerotanae incertae sedis      Chaetocerotaceae       Chaetoceros     didymus         20-40      1   \n",
       "10         Chaetoceros socialis  149123.0  Chromista  Heterokontophyta  Bacillariophyceae  Chaetocerotanae incertae sedis      Chaetocerotaceae       Chaetoceros    socialis         10-20      1   \n",
       "11  Chrysochromulina lanceolata  388470.0  Chromista        Haptophyta  Coccolithophyceae                    Prymnesiales  Chrysochromulinaceae  Chrysochromulina  lanceolata         10-20      3   \n",
       "12                  Cryptophyta   17638.0  Chromista       Cryptophyta               None                            None                  None              None        None           <10      1   \n",
       "13                  Dinophyceae   19542.0  Chromista           Myzozoa        Dinophyceae                            None                  None              None        None         10-20      1   \n",
       "14                  Dinophyceae   19542.0  Chromista           Myzozoa        Dinophyceae                            None                  None              None        None         20-40      1   \n",
       "\n",
       "    Abundance (counts/ml)    Avg Biovol    SD biovol    Avg ESD    SD ESD  Autoclass Version Autoclass Accuracy  Volume_ml      Sample_time_PT             IFCB_filename  \n",
       "0                0.220429   1299.804919     0.000000  13.472703  0.000000                  1               1; 0     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "1                2.204294    878.235876   387.536609  12.321494  1.947841                  1               0.94     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "2                0.220429   2809.605265     0.000000  23.481269  0.000000                  1          0.68; 0.5     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "3                0.661288   1192.529558   324.453840  16.053818  1.951944                  1               0.83     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "4                0.440859    584.857261    79.718365   9.749210  0.347502                  1         0.99; 0.66     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "5               21.822510   1104.680295   742.167223  14.963273  2.402542                  1         0.99; 0.66     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "6                3.526870   2428.623983  1093.145694  23.545662  3.301127                  1         0.99; 0.66     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "7                0.220429  23198.085547     0.000000  51.799277  0.000000                  1         0.99; 0.66     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "8                0.661288    938.681214   263.151930  13.436411  4.027888                  1               0.57     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "9                0.220429   1739.010744     0.000000  20.815810  0.000000                  1               0.57     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "10               0.220429    873.698658     0.000000  17.850499  0.000000                  1               0.45     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "11               0.661288    679.414864   404.491842  11.886907  0.490289                  1               0.16     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "12               0.220429    296.793514     0.000000   9.994931  0.000000                  1              0.834     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "13               0.220429   2781.178877     0.000000  17.305364  0.000000                  1         0.99; 0.31     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  \n",
       "14               0.220429   5200.338704     0.000000  21.309969  0.000000                  1         0.99; 0.31     4.5366 2022-08-14 16:38:43  D20220814T233843_IFCB151  "
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Column order: same as the original summary, WoRMS columns after Taxa, Count before abundance\n",
    "ORDER = ([\"Cruise\", \"Date\", \"Cast_Time\", \"Line\", \"Station\", \"Latitude\", \"Longitude\", \"Bottle\", \"Depth\", \"Depthstype\",\n",
    "          \"Taxa\"] + ([\"Autoclass classes\"] if GROUP_BY == \"worms\" else [])\n",
    "         + [\"WoRMS matched name\", \"AphiaID\", \"Kingdom\", \"Phylum\", \"Class\", \"Order\", \"Family\", \"Genus\", \"Species\",\n",
    "            \"Sizerange ESD\", \"Count\", \"Abundance (counts/ml)\", \"Avg Biovol\", \"SD biovol\", \"Avg ESD\", \"SD ESD\",\n",
    "            \"Autoclass Version\", \"Autoclass Accuracy\", \"Volume_ml\", \"Sample_time_PT\", \"IFCB_filename\"])\n",
    "ORDER = [c for c in ORDER if c in summary.columns]\n",
    "\n",
    "summary[\"Sizerange ESD\"] = pd.Categorical(summary[\"Sizerange ESD\"], categories=SIZE_BIN_LABELS, ordered=True)\n",
    "summary = (summary.sort_values([\"IFCB_filename\", \"Taxa\", \"Sizerange ESD\"])\n",
    "                  [ORDER].reset_index(drop=True))\n",
    "summary.head(15)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06f89da2",
   "metadata": {},
   "source": [
    "## 9. QC and export"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "fa36e930",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "QC:\n",
      "  all good\n"
     ]
    },
    {
     "data": {
      "application/vnd.microsoft.datawrangler.viewer.v0+json": {
       "columns": [
        {
         "name": "IFCB_filename",
         "rawType": "string",
         "type": "string"
        },
        {
         "name": "taxa",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "rois",
         "rawType": "int64",
         "type": "integer"
        },
        {
         "name": "total_per_ml",
         "rawType": "float64",
         "type": "float"
        }
       ],
       "ref": "36e1e387-8250-43d2-bf63-434151cc21b4",
       "rows": [
        [
         "D20220814T233843_IFCB151",
         "22",
         "381",
         "83.98360005290306"
        ],
        [
         "D20220815T000738_IFCB151",
         "38",
         "1638",
         "508.1748518598951"
        ]
       ],
       "shape": {
        "columns": 3,
        "rows": 2
       }
      },
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>taxa</th>\n",
       "      <th>rois</th>\n",
       "      <th>total_per_ml</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>IFCB_filename</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>D20220814T233843_IFCB151</th>\n",
       "      <td>22</td>\n",
       "      <td>381</td>\n",
       "      <td>83.983600</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>D20220815T000738_IFCB151</th>\n",
       "      <td>38</td>\n",
       "      <td>1638</td>\n",
       "      <td>508.174852</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                          taxa  rois  total_per_ml\n",
       "IFCB_filename                                     \n",
       "D20220814T233843_IFCB151    22   381     83.983600\n",
       "D20220815T000738_IFCB151    38  1638    508.174852"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qc = []\n",
    "if summary[\"Volume_ml\"].isna().any():\n",
    "    n = summary.loc[summary[\"Volume_ml\"].isna(), \"IFCB_filename\"].nunique()\n",
    "    qc.append(f\"{n} bin(s) have no volume analyzed -> Abundance is blank. Check the .hdr file is in DATA_DIR.\")\n",
    "if summary[\"WoRMS matched name\"].isna().any():\n",
    "    qc.append(f\"Taxa without a WoRMS name: {sorted(summary.loc[summary['WoRMS matched name'].isna(), 'Taxa'].unique())}\")\n",
    "if roi[\"ESD_um\"].isna().any():\n",
    "    qc.append(f\"{roi['ESD_um'].isna().sum()} ROI(s) with missing EquivDiameter.\")\n",
    "print(\"QC:\\n  \" + (\"\\n  \".join(qc) if qc else \"all good\"))\n",
    "\n",
    "# Per-bin totals — quick sanity check\n",
    "per_bin = summary.groupby(\"IFCB_filename\").agg(taxa=(\"Taxa\", \"nunique\"), rois=(\"Count\", \"sum\"),\n",
    "                                               total_per_ml=(\"Abundance (counts/ml)\", \"sum\"))\n",
    "per_bin.head(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "12db882e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wrote CalCOFI_CTD_summary_output/CalCOFI_CTD_IFCB_data_summary_new.csv and CalCOFI_CTD_summary_output/CalCOFI_CTD_IFCB_data_summary_new.xlsx\n",
      "Wrote CalCOFI_CTD_summary_output/CalCOFI_CTD_IFCB_data_summary_new_roi_level.csv (all ROIs, before taxa filtering)\n"
     ]
    }
   ],
   "source": [
    "OUTPUT_DIR.mkdir(parents=True, exist_ok=True)\n",
    "out_csv  = OUTPUT_DIR / f\"{OUTPUT_NAME}.csv\"\n",
    "out_xlsx = OUTPUT_DIR / f\"{OUTPUT_NAME}.xlsx\"\n",
    "\n",
    "summary.to_csv(out_csv, index=False)\n",
    "with pd.ExcelWriter(out_xlsx) as xw:\n",
    "    summary.to_excel(xw, sheet_name=\"summary\", index=False)\n",
    "    class_map.reset_index().to_excel(xw, sheet_name=\"class_to_WoRMS\", index=False)\n",
    "    per_bin.reset_index().to_excel(xw, sheet_name=\"per_bin_totals\", index=False)\n",
    "print(\"Wrote\", out_csv, \"and\", out_xlsx)\n",
    "\n",
    "if SAVE_ROI_TABLE:\n",
    "    roi_out = OUTPUT_DIR / f\"{OUTPUT_NAME}_roi_level.csv\"\n",
    "    roi.merge(meta[[\"bin\", \"Volume_ml\"]], on=\"bin\", how=\"left\").to_csv(roi_out, index=False)\n",
    "    print(\"Wrote\", roi_out, \"(all ROIs, before taxa filtering)\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
